Expo 相机
一个 React 组件,用于渲染设备前置或后置摄像头的预览。
For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.
expo-camera 提供了一个 React 组件,用于渲染设备前置或后置摄像头的预览。摄像头的参数,例如缩放、闪光灯和闪光模式,都可以调整。使用 CameraView,你可以拍照和录制视频,并保存到应用的缓存中。该组件还能够检测预览中出现的条形码。在你的设备上运行 示例 来查看这些功能如何协同工作。
安装
- npx expo install expo-cameraIf you are installing this in an existing React Native app, make sure to install expo in your project.
在 app 配置中进行配置
如果你在项目中使用 config plugins(Continuous Native Generation (CNG)),你可以使用 expo-camera 内置的 config plugin 进行配置。该插件允许你配置一些无法在运行时设置、并且需要重新构建新的应用二进制文件后才会生效的属性。如果你的应用没有使用 CNG,那么你需要手动配置该库。
Example app.json with config plugin
{ "expo": { "plugins": [ [ "expo-camera", { "cameraPermission": "允许 $(PRODUCT_NAME) 访问你的摄像头", "microphonePermission": "允许 $(PRODUCT_NAME) 访问你的麦克风", "recordAudioAndroid": true } ] ] } }
Configurable properties
| Name | Default | Description |
|---|---|---|
cameraPermission | "允许 $(PRODUCT_NAME) 访问你的摄像头" | Only for: iOS 用于设置 |
microphonePermission | "允许 $(PRODUCT_NAME) 访问你的麦克风" | Only for: iOS 用于设置 |
recordAudioAndroid | true | Only for: Android 一个布尔值,用于决定是否在 Android 上启用 |
Are you using this library in an existing React Native app?
如果你没有使用 Continuous Native Generation(CNG)(也就是你在手动使用原生 android 和 ios 项目),那么你需要在原生项目中配置以下权限:
Android
-
expo-camera会自动将android.permission.CAMERA权限添加到你项目的 android/app/src/main/AndroidManifest.xml 中。如果你想录制带音频的视频,请包含RECORD_AUDIO权限:<!-- 已添加的权限 --> <uses-permission android:name="android.permission.CAMERA" /> <!-- 仅在录制带音频的视频时添加 --> <uses-permission android:name="android.permission.RECORD_AUDIO" /> -
然后,调整 android/build.gradle 文件,在所有其他仓库后添加一个新的 maven 块,如下所示:
allprojects { repositories { // * 你的其他仓库放在这里 * // * 在其他仓库 / 块之后添加一个新的 maven 块 * maven { // expo-camera 捆绑了一个自定义的 com.google.android:cameraview url "$rootDir/../node_modules/expo-camera/android/maven" } } }
iOS
-
将
NSCameraUsageDescription和NSMicrophoneUsageDescription键添加到你项目的 ios/[app]/Info.plist 中:<key>NSCameraUsageDescription</key> <string>允许 $(PRODUCT_NAME) 访问你的摄像头</string> <key>NSMicrophoneUsageDescription</key> <string>允许 $(PRODUCT_NAME) 访问你的麦克风</string>
使用
在任意给定时间内,只能有一个 Camera 预览处于活动状态。如果你的应用有多个屏幕,当某个屏幕失去焦点时,你应该卸载Camera组件。
import { CameraView, CameraType, useCameraPermissions } from 'expo-camera'; import { useState } from 'react'; import { Button, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; export default function App() { const [facing, setFacing] = useState<CameraType>('back'); const [permission, requestPermission] = useCameraPermissions(); if (!permission) { // 摄像头权限仍在加载中。 return <View />; } if (!permission.granted) { // 摄像头权限尚未授予。 return ( <View style={styles.container}> <Text style={styles.message}>我们需要你的许可来显示摄像头</Text> <Button onPress={requestPermission} title="授予权限" /> </View> ); } function toggleCameraFacing() { setFacing(current => (current === 'back' ? 'front' : 'back')); } return ( <View style={styles.container}> <CameraView style={styles.camera} facing={facing} /> <View style={styles.buttonContainer}> <TouchableOpacity style={styles.button} onPress={toggleCameraFacing}> <Text style={styles.text}>翻转摄像头</Text> </TouchableOpacity> </View> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', }, message: { textAlign: 'center', paddingBottom: 10, }, camera: { flex: 1, }, buttonContainer: { position: 'absolute', bottom: 64, flexDirection: 'row', backgroundColor: 'transparent', width: '100%', paddingHorizontal: 64, }, button: { flex: 1, alignItems: 'center', }, text: { fontSize: 24, fontWeight: 'bold', color: 'white', }, });
高级用法
一个完整示例,展示如何拍照并将其显示出来。使用 TypeScript 编写。
Web 支持
大多数浏览器都支持某种版本的网页摄像头功能,你可以在 这里查看网页摄像头的浏览器支持情况。图像 URI 总是以 base64 字符串返回,因为浏览器中不可用本地文件系统路径。
Chrome iframe 用法
当使用 Chrome 64 及以上版本 时,如果你尝试在跨域 iframe 中使用网页摄像头,将不会渲染任何内容。要为你的 iframe 添加摄像头支持,只需向 iframe 元素添加属性 allow="microphone; camera;":
<iframe src="..." allow="microphone; camera;"> <!-- <CameraView /> --> </iframe>
API
import { CameraView } from 'expo-camera';
Component
Type: React.Component<CameraViewProps>
boolean • Default: trueA boolean that determines whether the camera should be active. Useful in situations where the camera may not have unmounted but you still want to stop the camera session.
boolean • Default: trueA boolean that determines whether the camera shutter animation should be enabled.
BarcodeSettingsExample
<CameraView barcodeScannerSettings={{ barcodeTypes: ["qr"], }} />
boolean • Default: falseA boolean to enable or disable the torch.
CameraType • Default: 'back'Camera facing. Use one of CameraType. When front, use the front-facing camera.
When back, use the back-facing camera.
FlashMode • Default: 'off'Camera flash mode. Use one of FlashMode values. When on, the flash on your device will
turn on when taking a picture. When off, it won't. Setting it to auto will fire flash if required.
boolean • Default: falseA boolean that determines whether the camera should mirror the image when using the front camera.
CameraMode • Default: 'picture'Used to select image or video output.
boolean • Default: falseIf present, video will be recorded with no sound.
(event: AvailableLenses) => voidCallback invoked when the cameras available lenses change.
event: AvailableLensesresult object that contains a lenses property containing an array of available lenses.
(scanningResult: BarcodeScanningResult) => voidCallback that is invoked when a barcode has been successfully scanned. The callback is provided with
an object of the BarcodeScanningResult shape, where the type
refers to the barcode type that was scanned, and the data is the information encoded in the barcode
(in this case of QR codes, this is often a URL). See BarcodeType for supported values.
() => voidCallback invoked when camera preview has been set.
(event: CameraMountError) => voidCallback invoked when camera preview could not start.
event: CameraMountErrorError object that contains a message.
(event: ResponsiveOrientationChanged) => voidCallback invoked when responsive orientation changes. Only applicable if responsiveOrientationWhenOrientationLocked is true.
event: ResponsiveOrientationChangedresult object that contains updated orientation of camera
stringA string representing the size of pictures takePictureAsync will take.
Available sizes can be fetched with getAvailablePictureSizesAsync.
Setting this prop will cause the ratio prop to be ignored as the aspect ratio is determined by the selected size.
CameraRatioA string representing the aspect ratio of the preview. For example, 4:3 and 16:9.
Note: Setting the aspect ratio here will change the scaleType of the camera preview from FILL to FIT.
Also, when using 1:1, devices only support certain sizes. If you specify an unsupported size, the closest supported ratio will be used.
booleanWhether to allow responsive orientation of the camera when the screen orientation is locked (that is, when set to true,
landscape photos will be taken if the device is turned that way, even if the app or device orientation is locked to portrait).
string • Default: 'builtInWideAngleCamera'Available lenses are emitted to the onAvailableLensesChanged callback whenever the currently selected camera changes or by calling getAvailableLensesAsync.
You can read more about the available lenses in the Apple documentation.
numberThe bitrate of the video recording in bits per second.
Note: On iOS, you must specify the video codec when calling recordAsync to use this option.
Example
10_000_000
VideoQualitySpecify the quality of the recorded video. Use one of VideoQuality possible values:
for 16:9 resolution 2160p, 1080p, 720p, 480p : Android only and for 4:3 4:3 (the size is 640x480).
If the chosen quality is not available for a device, the highest available is chosen.
VideoStabilizationThe video stabilization mode used for a video recording. Use one of VideoStabilization.<value>.
You can read more about each stabilization type in Apple Documentation.
number • Default: 0A value between 0 and 1 being a percentage of device's max zoom, where 0 means not zoomed and 1 means maximum zoom.
Static Methods
Dismiss the scanner presented by launchScanner.
On Android, the scanner is dismissed automatically when a barcode is scanned.
Promise<void>Queries the device for the available video codecs that can be used in video recording.
Promise<VideoCodec[]>A promise that resolves to a list of strings that represents available codecs.
Check whether the current device has a camera. This is useful for web and simulators cases. This isn't influenced by the Permissions API (all platforms), or HTTP usage (in the browser). You will still need to check if the native permission has been accepted.
Promise<boolean>| Parameter | Type |
|---|---|
| options(optional) | ScanningOptions |
On Android, we will use the Google code scanner.
On iOS, presents a modal view controller that uses the DataScannerViewController available on iOS 16+.
Promise<void>| Parameter | Type | Description |
|---|---|---|
| listener | (event: ScanningResult) => void | Invoked with the ScanningResult when a bar code has been successfully scanned. |
Invokes the listener function when a bar code has been successfully scanned. The callback is provided with
an object of the ScanningResult shape, where the type refers to the bar code type that was scanned and the data is the information encoded in the bar code
(in this case of QR codes, this is often a URL). See BarcodeType for supported values.
EventSubscriptionComponent Methods
Returns the available lenses for the currently selected camera.
Promise<string[]>Returns a Promise that resolves to an array of strings representing the lens type that can be passed to selectedLens prop.
Get picture sizes that are supported by the device.
Promise<string[]>Returns a Promise that resolves to an array of strings representing picture sizes that can be passed to pictureSize prop.
The list varies across Android devices but is the same for every iOS.
Returns an object with the supported features of the camera on the current device.
{
isModernBarcodeScannerAvailable: boolean,
toggleRecordingAsyncAvailable: boolean
}Pauses the camera preview. It is not recommended to use takePictureAsync when preview is paused.
Promise<void>| Parameter | Type | Description |
|---|---|---|
| options(optional) | CameraRecordingOptions | A map of |
Starts recording a video that will be saved to cache directory. Videos are rotated to match device's orientation. Flipping camera during a recording results in stopping it.
Promise<undefined | {
uri: string
}>Returns a Promise that resolves to an object containing video file uri property and a codec property on iOS.
The Promise is returned if stopRecording was invoked, one of maxDuration and maxFileSize is reached or camera preview is stopped.
Resumes the camera preview.
Promise<void>| Parameter | Type | Description |
|---|---|---|
| options | CameraPictureOptions & {
pictureRef: true
} | An object in form of |
Takes a picture and saves it to app's cache directory. Photos are rotated to match device's orientation
(if options.skipProcessing flag is not enabled) and scaled to match the preview.
Note: Make sure to wait for the
onCameraReadycallback before calling this method.
Promise<PictureRef>Returns a Promise that resolves to CameraCapturedPicture object, where uri is a URI to the local image file on Android,
iOS, and a base64 string on web (usable as the source for an Image element). The width and height properties specify
the dimensions of the image.
base64 is included if the base64 option was truthy, and is a string containing the JPEG data
of the image in Base64. Prepend it with 'data:image/jpg;base64,' to get a data URI, which you can use as the source
for an Image element for example.
exif is included if the exif option was truthy, and is an object containing EXIF
data for the image. The names of its properties are EXIF tags and their values are the values for those tags.
On native platforms, the local image URI is temporary. Use
FileSystem.copyAsyncto make a permanent copy of the image.
Note: Avoid calling this method while the preview is paused. On Android, this will throw an error. On iOS, this will take a picture of the last frame that is currently on screen.
| Parameter | Type | Description |
|---|---|---|
| options(optional) | CameraPictureOptions | An object in form of |
Takes a picture and saves it to app's cache directory. Photos are rotated to match device's orientation
(if options.skipProcessing flag is not enabled) and scaled to match the preview.
Note: Make sure to wait for the
onCameraReadycallback before calling this method.
Promise<CameraCapturedPicture>Returns a Promise that resolves to CameraCapturedPicture object, where uri is a URI to the local image file on Android,
iOS, and a base64 string on web (usable as the source for an Image element). The width and height properties specify
the dimensions of the image.
base64 is included if the base64 option was truthy, and is a string containing the JPEG data
of the image in Base64. Prepend it with 'data:image/jpg;base64,' to get a data URI, which you can use as the source
for an Image element for example.
exif is included if the exif option was truthy, and is an object containing EXIF
data for the image. The names of its properties are EXIF tags and their values are the values for those tags.
On native platforms, the local image URI is temporary. Use
FileSystem.copyAsyncto make a permanent copy of the image.
Note: Avoid calling this method while the preview is paused. On Android, this will throw an error. On iOS, this will take a picture of the last frame that is currently on screen.
Pauses or resumes the video recording. Only has an effect if there is an active recording. On iOS, this method only supported on iOS 18.
Promise<undefined | void>Example
const { toggleRecordingAsyncAvailable } = getSupportedFeatures() return ( {toggleRecordingAsyncAvailable && ( <Button title="Toggle Recording" onPress={toggleRecordingAsync} /> )} )
Hooks
| Parameter | Type |
|---|---|
| options(optional) | PermissionHookOptions<object> |
Check or request permissions to access the camera.
This uses both requestCameraPermissionsAsync and getCameraPermissionsAsync to interact with the permissions.
[null | PermissionResponse, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]Example
const [status, requestPermission] = useCameraPermissions();
| Parameter | Type |
|---|---|
| options(optional) | PermissionHookOptions<object> |
Check or request permissions to access the microphone.
This uses both requestMicrophonePermissionsAsync and getMicrophonePermissionsAsync to interact with the permissions.
[null | PermissionResponse, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]Example
const [status, requestPermission] = Camera.useMicrophonePermissions();
Classes
Type: Class extends _default<CameraEvents>
CameraNativeModule Properties
() => Promise<void>() => Promise<VideoCodec[]>() => Promise<PermissionResponse>() => Promise<PermissionResponse>() => Promise<boolean>(options?: ScanningOptions) => Promise<void>() => Promise<PermissionResponse>() => Promise<PermissionResponse>(url: string, barcodeTypes?: BarcodeType[]) => Promise<BarcodeScanningResult[]>Type: Class extends SharedRef<'image'>
A reference to a native instance of the image.
PictureRef Properties
PictureRef Methods
| Parameter | Type | Description |
|---|---|---|
| options(optional) | SavePictureOptions | A map defining how modified image should be saved. |
Saves the image to the file system in the cache directory.
Promise<PhotoResult>Methods
| Parameter | Type | Description |
|---|---|---|
| url | string | URL to get the image from. |
| barcodeTypes(optional) | BarcodeType[] | An array of bar code types. Defaults to all supported bar code types on the platform.
|
Scan bar codes from the image at the given URL.
Promise<BarcodeScanningResult[]>A possibly empty array of objects of the BarcodeScanningResult shape, where the type
refers to the barcode type that was scanned and the data is the information encoded in the barcode.
Interfaces
A subscription object that allows to conveniently remove an event listener from the emitter.
Types
| Property | Type | Description |
|---|---|---|
| origin | BarcodePoint | The origin point of the bounding box. |
| size | BarcodeSize | The size of the bounding box. |
Type: Point
These coordinates are represented in the coordinate space of the camera source (e.g. when you are using the camera view, these values are adjusted to the dimensions of the view).
| Property | Type | Description |
|---|---|---|
| bounds | BarcodeBounds | The |
| cornerPoints | BarcodePoint[] | Corner points of the bounding box.
|
| data | string | The parsed information encoded in the barcode. |
| extra(optional) | AndroidBarcode | Only for: Android Extra information returned by the specific type of barcode. |
| type | string | The barcode type. |
| Property | Type | Description |
|---|---|---|
| barcodeTypes | BarcodeType[] | - |
| Property | Type | Description |
|---|---|---|
| height | number | The height value. |
| width | number | The width value. |
Literal Type: string
The available barcode types that can be scanned.
Acceptable values are: 'aztec' | 'ean13' | 'ean8' | 'qr' | 'pdf417' | 'upc_e' | 'datamatrix' | 'code39' | 'code93' | 'itf14' | 'codabar' | 'code128' | 'upc_a'
| Property | Type | Description |
|---|---|---|
| base64(optional) | string | A Base64 representation of the image. |
| exif(optional) | Partial<MediaTrackSettings> | any | On Android and iOS this object may include various fields based on the device and operating system.
On web, it is a partial representation of the |
| format | 'jpg' | 'png' | The format of the captured image. |
| height | number | Captured image height. |
| uri | string | On web, the value of |
| width | number | Captured image width. |
| Property | Type | Description |
|---|---|---|
| onModernBarcodeScanned | (event: ScanningResult) => void | - |
Literal Type: string
Acceptable values are: 'portrait' | 'portraitUpsideDown' | 'landscapeLeft' | 'landscapeRight'
| Property | Type | Description |
|---|---|---|
| additionalExif(optional) | Record<string, any> | Only for: Android iOS Additional EXIF data to be included for the image. Only useful when |
| base64(optional) | boolean | Whether to also include the image data in Base64 format. |
| exif(optional) | boolean | Whether to also include the EXIF data for the image. |
| imageType(optional) | ImageType | Only for: -Web |
| isImageMirror(optional) | boolean | Only for: -Web |
| mirror(optional) | boolean |
Android iOS When set to Default: false |
| onPictureSaved(optional) | (picture: CameraCapturedPicture) => void | A callback invoked when picture is saved. If set, the promise of this method will resolve immediately with no data after picture is captured. The data that it should contain will be passed to this callback. If displaying or processing a captured photo right after taking it is not your case, this callback lets you skip waiting for it to be saved. |
| pictureRef(optional) | boolean | Whether the camera should return an image ref that can be used directly in the |
| quality(optional) | number | Specify the compression quality from Default: 1 |
| scale(optional) | number | Only for: -Web |
| shutterSound(optional) | boolean | To programmatically disable the camera shutter sound Default: true |
| skipProcessing(optional) | boolean | If set to
|
| Property | Type | Description |
|---|---|---|
| codec(optional) | VideoCodec | Only for: iOS This option specifies what codec to use when recording the video. See |
| maxDuration(optional) | number | Maximum video duration in seconds. |
| maxFileSize(optional) | number | Maximum video file size in bytes. |
| mirror(optional) | boolean |
If |
Literal Type: string
This option specifies the mode of focus on the device.
on- Indicates that the device should autofocus once and then lock the focus.off- Indicates that the device should automatically focus when needed.
Default:off
Acceptable values are: 'on' | 'off'
Literal Type: union
Permission expiration time. Currently, all permissions are granted permanently.
Acceptable values are: 'never' | number
Literal Type: union
Acceptable values are: PermissionHookBehavior | Options
An object obtained by permissions get and request functions.
| Property | Type | Description |
|---|---|---|
| canAskAgain | boolean | Indicates if user can be asked again for specific permission. If not, one should be directed to the Settings app in order to enable/disable the permission. |
| expires | PermissionExpiration | Determines time when the permission expires. |
| granted | boolean | A convenience boolean that indicates if the permission is granted. |
| status | PermissionStatus | Determines the status of the permission. |
| Property | Type | Description |
|---|---|---|
| base64(optional) | string | A Base64 representation of the image. |
| height | number | Height of the image. |
| uri | string | A URI to the modified image (usable as the source for an |
| width | number | Width of the image. |
| Property | Type | Description |
|---|---|---|
| orientation | CameraOrientation | - |
A map defining how modified image should be saved.
| Property | Type | Description |
|---|---|---|
| base64(optional) | boolean | Whether to also include the image data in Base64 format. |
| metadata(optional) | Record<string, any> | Additional metadata to be included for the image. |
| quality(optional) | number | Specify the compression quality from |
| Property | Type | Description |
|---|---|---|
| barcodeTypes | BarcodeType[] | The type of codes to scan for. |
| isGuidanceEnabled(optional) | boolean | Only for: iOS Guidance text, such as “Slow Down,” appears over the live video. Default: true |
| isHighlightingEnabled(optional) | boolean | Only for: iOS Indicates whether the scanner displays highlights around recognized items. Default: false |
| isPinchToZoomEnabled(optional) | boolean | Only for: iOS Indicates whether people can use a two-finger pinch-to-zoom gesture. Default: true |
Type: Omit<BarcodeScanningResult, 'bounds' | 'cornerPoints'>
Literal Type: string
This option specifies what codec to use when recording a video.
Acceptable values are: 'avc1' | 'hvc1' | 'jpeg' | 'apcn' | 'ap4h'
Literal Type: string
Acceptable values are: '2160p' | '1080p' | '720p' | '480p' | '4:3'
Literal Type: string
This option specifies the stabilization mode to use when recording a video.
Acceptable values are: 'off' | 'standard' | 'cinematic' | 'auto'
Enums
权限
Android
此包会自动向你的应用添加 CAMERA 权限。如果你想录制带音频的视频,你必须在 app.json 的 expo.android.permissions 数组中包含 RECORD_AUDIO。
| Android Permission | Description |
|---|---|
Required to be able to access the camera device. | |
Allows an application to record audio. |
iOS
此库使用以下用途说明键: