首页指南参考教程

使用图片选择器

在本教程中,学习如何使用 Expo Image Picker。


React Native 提供了内置组件,这些组件是每个应用使用的标准构建块,例如 <View><Text><Pressable>。我们想要构建一个使用这些核心组件和 API 无法实现的功能:从设备的媒体库中选择图片。为此,我们需要一个库。

¥React Native provides built-in components that are standard building blocks used by every application, such as <View>, <Text>, and <Pressable>. We want to build a feature that isn't possible with these core components and API: selecting an image from the device's media library. For that, we will need a library.

为了实现这一点,我们将使用一个名为 expo-image-picker 的 Expo SDK 库。

¥To achieve this, we'll use an Expo SDK library called expo-image-picker.

expo-image-picker 提供对系统 UI 的访问,以从手机库中选择图片和视频或使用相机拍照。

¥expo-image-picker provides access to the system's UI to select images and videos from the phone's library or take a photo with the camera.

1

安装 expo-image-picker

¥Install expo-image-picker

要安装该库,请运行以下命令:

¥To install the library, run the following command:

Terminal
npx expo install expo-image-picker

提示:每当我们在项目中安装新库时,都必须通过在终端中按 Ctrl + c 然后运行安装命令来停止开发服务器。安装后,我们可以通过从同一终端窗口运行 npx expo start 来再次启动开发服务器。

¥Tip: Any time we install a new library in our project, we must stop the development server by pressing Ctrl + c in the terminal and then running the installation command. After the installation, we can start the development server again by running npx expo start from the same terminal window.

2

从设备的媒体库中选择图片

¥Pick an image from the device's media library

expo-image-picker 提供了 launchImageLibraryAsync() 方法,该方法显示用于从设备的媒体库中选择图片或视频的系统 UI。

¥expo-image-picker provides the launchImageLibraryAsync() method that displays the system UI for choosing an image or a video from the device's media library.

我们可以使用上一章中创建的主主题按钮从设备的媒体库中选择图片。我们将创建一个函数来启动设备的图片库来实现此功能。

¥We can use the button with the primary theme we created in the previous chapter to pick an image from the device's media library. We'll create a function to launch the device's image library to implement this functionality.

在 App.js 中,导入 expo-image-picker 库并在 App 组件内创建 pickImageAsync() 函数:

¥In App.js, import the expo-image-picker library and create a pickImageAsync() function inside the App component:

App.js
// ...rest of the import statements remain unchanged
import * as ImagePicker from 'expo-image-picker';

export default function App() {
  const pickImageAsync = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      quality: 1,
    });

    if (!result.canceled) {
      console.log(result);
    } else {
      alert('You did not select any image.');
    }
  };

  // ...rest of the code remains same
}

我们来了解一下上面的代码做了什么。

¥Let's learn what the above code does.

  • launchImageLibraryAsync() 接收一个指定了不同选项的对象。该对象是 ImagePickerOptions object。我们可以在调用方法时传递对象来指定不同的选项。

    ¥The launchImageLibraryAsync() receives an object in which different options are specified. This object is an ImagePickerOptions object. We can pass the object to specify different options when invoking the method.

  • allowsEditing 设置为 true 时,用户可以在 Android 和 iOS 上的选择过程中裁剪图片,但不能在 Web 上裁剪图片。

    ¥When allowsEditing is set to true, the user can crop the image during the selection process on Android and iOS but not on the web.

3

更新按钮组件

¥Update the button component

当主按钮被按下时,我们需要调用 pickImageAsync() 函数。要调用它,请更新 Components/Button.js 中 <Button> 组件的 onPress 属性:

¥When the primary button gets pressed, we need to call the pickImageAsync() function. To call it, update the onPress property of the <Button> component in components/Button.js:

Button.js
export default function Button({ label, theme, onPress}) {
  // ...rest of the code remains same
  if (theme === "primary") {
    return (
      <View>
        

{/* ...rest of the code remains same */}


        <Pressable
          style={[styles.button, { backgroundColor: '#fff' }]}
          onPress=

{onPress}


        >
      </View>
    );
  }
}

在 App.js 中,将 pickImageAsync() 函数添加到第一个 <Button> 上的 onPress 属性中。

¥In App.js, add the pickImageAsync() function to the onPress prop on the first <Button>.

App.js
export default function App() {
  // ...rest of the code remains same

  return (
    <View style={styles.container}>
      

{/* ...rest of the code remains same */}


      <Button theme="primary" label="Choose a photo" onPress=

{pickImageAsync}

 />
    </View>
  );
}

pickImageAsync() 函数负责调用 ImagePicker.launchImageLibraryAsync(),然后处理结果。launchImageLibraryAsync() 方法返回一个对象,其中包含有关所选图片的信息。

¥The pickImageAsync() function is responsible for invoking ImagePicker.launchImageLibraryAsync() and then handling the result. The launchImageLibraryAsync() method returns an object containing information about the selected image.

为了演示 result 对象包含哪些属性,下面是一个结果对象示例:

¥To demonstrate what properties the result object contains, here is an example result object:

{
  "assets": [
    {
      "assetId": null,
      "base64": null,
      "duration": null,
      "exif": null,
      "height": 4800,
      "rotation": null,
      "type": "image",
      "uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%username%252Fsticker-smash-47-beta/ImagePicker/77c4e56f-4ccc-4c83-8634-fc376597b6fb.jpeg",
      "width": 3200
    }
  ],
  "canceled": false
}

4

使用选定的图片

¥Use the selected image

result 对象提供 assets 数组,其中包含所选图片的 uri。让我们从图片选择器中获取该值,并使用它在应用中显示选定的图片。

¥The result object provides the assets array, which contains the uri of the selected image. Let's take this value from the image picker and use it to show the selected image in the app.

按照以下步骤修改 App.js 文件:

¥Modify the App.js file in the following steps:

  • 使用 React 中的 useState 钩子声明一个名为 selectedImage 的状态变量。我们将使用此状态变量来保存所选图片的 URI。

    ¥Declare a state variable called selectedImage using the useState hook from React. We'll use this state variable to hold the URI of the selected image.

  • 更新 pickImageAsync() 函数以将图片 URI 保存在 selectedImage 状态变量中。

    ¥Update the pickImageAsync() function to save the image URI in the selectedImage state variable.

  • 然后,将 selectedImage 作为 prop 传递给 ImageViewer 组件。

    ¥Then, pass the selectedImage as a prop to the ImageViewer component.

App.js
import { useState } from 'react';
// ...rest of the import statements remain unchanged

export default function App() {
  const [selectedImage, setSelectedImage] = useState(null);

  const pickImageAsync = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      allowsEditing: true,
      quality: 1,
    });

    if (!result.canceled) {
      setSelectedImage(result.assets[0].uri);
    } else {
      alert('You did not select any image.');
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.imageContainer}>
        <ImageViewer
          placeholderImageSource={PlaceholderImage}
          selectedImage={selectedImage}
        />
      </View>
      

{/* ...rest of the code remains same */}


    </View>
  );
}

现在,修改 Components/ImageViewer.js 文件以有条件地显示所选图片来代替占位符图片。我们需要将 selectedImage 属性传递给组件。

¥Now, modify the components/ImageViewer.js file to conditionally display the selected image in place of the placeholder image. We'll need to pass the selectedImage prop to the component.

图片源越来越长,所以我们也将其移动到一个名为 imageSource 的单独变量中。然后,将其作为 <Image> 组件上 source 属性的值传递。

¥The source of the image is getting long, so let's also move it to a separate variable called imageSource. Then, pass it as the value of the source prop on the <Image> component.

Image picker
export default function ImageViewer({ placeholderImageSource, selectedImage }) {
  const imageSource = selectedImage  ? { uri: selectedImage } : placeholderImageSource;

  return <Image source={imageSource} style={styles.image} />;
}

在上面的代码片段中,<Image> 组件使用条件运算符来加载图片源。这是因为从图片选择器中选取的图片是 uri string,而不是像占位符图片那样的本地资源。

¥In the above snippet, the <Image> component uses a conditional operator to load the source of the image. This is because the image picked from the image picker is a uri string, not a local asset like the placeholder image.

现在让我们看看我们的应用:

¥Let's take a look at our app now:

本教程中用于演示的图片选自 未飞溅

¥The images used for the demo in this tutorial were picked from Unsplash.

下一步

¥Next step

我们添加了从设备媒体库中选取图片的功能。

¥We added the functionality to pick an image from the device's media library.

创建表情符号选择器模式

在下一章中,我们将学习如何创建表情符号选择器模态组件。

Expo 中文网 - 粤ICP备13048890号