This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
Expo 摄像头
用于渲染设备前置或后置摄像头预览的 React 组件。
expo-camera 提供了一个 React 组件,用于渲染设备前置或后置摄像头的预览。摄像头的变焦、闪光灯和闪光模式等参数均可调整。使用 CameraView,你可以拍摄照片和录制视频,文件会保存到应用的缓存中。该组件还能够检测预览画面中出现的条形码。在设备上运行示例,即可查看这些功能如何协同工作。
安装
If you are installing this in an existing React Native app, make sure to install expo in your project.
在应用配置中进行配置
如果项目使用配置插件(Continuous Native Generation (CNG)),你可以使用 expo-camera 内置的配置插件进行配置。该插件允许你配置各种无法在运行时设置的属性,这些属性需要重新构建应用二进制文件才能生效。如果应用不使用 CNG,则需要手动配置此库。
Example app.json with config plugin
Configurable properties
若要本地化 iOS 摄像头或麦克风权限提示,请在每个语言区域文件的 ios 对象中添加 NSCameraUsageDescription 或 NSMicrophoneUsageDescription。将 cameraPermission 和 microphonePermission 保持为默认值。Expo 会在 prebuild 期间将本地化后的值写入 InfoPlist.strings。
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权限:<!-- Added permission --> <uses-permission android:name="android.permission.CAMERA" /> <!-- Only add when recording videos with audio --> <uses-permission android:name="android.permission.RECORD_AUDIO" /> -
然后,调整 android/build.gradle 文件,在其他所有仓库之后添加新的 maven 代码块,如下所示:
allprojects { repositories { // * Your other repositories here * // * Add a new maven block after other repositories / blocks * maven { // expo-camera bundles a custom com.google.android:cameraview url "$rootDir/../node_modules/expo-camera/android/maven" } } }
iOS
-
在项目的 ios/[app]/Info.plist 中添加
NSCameraUsageDescription和NSMicrophoneUsageDescription键:<key>NSCameraUsageDescription</key> <string>Allow $(PRODUCT_NAME) to access your camera</string> <key>NSMicrophoneUsageDescription</key> <string>Allow $(PRODUCT_NAME) to access your microphone</string>
用法
任意时刻只能有一个摄像头预览处于活动状态。如果应用中有多个屏幕,则应在屏幕失去焦点时卸载
Camera组件。
高级用法
A complete example that shows how to take a picture and display it. Written in TypeScript.
Web 支持
大多数浏览器都支持某种形式的网络摄像头功能,你可以在此处查看网络摄像头浏览器支持情况。由于浏览器中无法使用本地文件系统路径,因此图像 URI 始终以 base64 字符串形式返回。
Chrome iframe 用法
使用 Chrome 64+ 版本时,如果尝试在跨域 iframe 中使用网络摄像头,将不会渲染任何内容。要在 iframe 中启用摄像头支持,只需将 allow="microphone; camera;" 属性添加到 iframe 元素:
<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: RecordingProgress) => voidCallback invoked repeatedly while a video recording is in progress.
The values are read from the native recorder, so they track the media actually written to disk.
Progress events are not delivered while the recording is paused.
The callback fires about every 500 milliseconds by default; configure the rate with
progressUpdateInterval in the recordAsync options.
event: RecordingProgressResult object that contains the recorded duration and fileSize, plus the
maxDuration passed to recordAsync when a limit was set.
(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).
stringThe deviceType identifier for the lens to use. Retrieve available lenses by calling
getAvailableLensesAsync or listening to the onAvailableLensesChanged
callback, then pass the deviceType value from the returned LensInfo objects.
Common values include:
"AVCaptureDeviceTypeBuiltInWideAngleCamera"- Standard wide angle camera"AVCaptureDeviceTypeBuiltInUltraWideCamera"- Ultra wide angle camera"AVCaptureDeviceTypeBuiltInTelephotoCamera"- Telephoto camera
If not specified or if the value doesn't match an available lens, the default camera for the current position (front/back) is used.
You can read more about device types in the Apple documentation.
Example
const lenses = await cameraRef.current.getAvailableLensesAsync(); const ultraWide = lenses.find(l => l.deviceType === 'AVCaptureDeviceTypeBuiltInUltraWideCamera'); if (ultraWide) { setSelectedLens(ultraWide.deviceType); }
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.
VideoStabilization • Default: 'auto'The 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>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>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.
EventSubscriptionPresents the system document scanner and returns the captured pages once the user saves. On iOS, this uses
VisionKit's VNDocumentCameraViewController;
on Android it uses the ML Kit document scanner.
The page images and the optional PDF are written to the app's cache directory, so copy them to a permanent
location with expo-file-system if you need to keep them.
Promise<DocumentScanningResult | null>A promise that resolves to a DocumentScanningResult, or null if the user
cancels the scan or the scanner is unavailable on the device.
Example
const result = await CameraView.scanDocumentAsync({ requestPdf: true }); if (result) { console.log(result.pages); // ['file:///.../DocumentScanner/<uuid>.jpg', ...] console.log(result.pdfUri); // 'file:///.../DocumentScanner/<uuid>.pdf' }
Component methods
Returns the available lenses for the currently selected camera.
Promise<LensInfo[]>An array of LensInfo objects containing both the stable deviceType identifier and the localizedName for display purposes. The deviceType can be passed to the 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>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<{
uri: string
} | undefined>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>Takes a picture and returns an object that references the native image instance.
Note: Make sure to wait for the
onCameraReadycallback before calling this method.
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.
Promise<PictureRef>Returns a Promise that resolves to PictureRef class which contains basic image data, and a reference to native image instance which can be passed
to other Expo packages supporting handling such an instance.
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.
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.
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.copyto make a permanent copy of the image.
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<void | undefined>Example
const { toggleRecordingAsyncAvailable } = getSupportedFeatures() return ( {toggleRecordingAsyncAvailable && ( <Button title="Toggle Recording" onPress={toggleRecordingAsync} /> )} )
Hooks
Check or request permissions to access the camera.
This uses both requestCameraPermissionsAsync and getCameraPermissionsAsync to interact with the permissions.
[PermissionResponse | null, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]Example
const [status, requestPermission] = useCameraPermissions();
Check or request permissions to access the microphone.
This uses both requestMicrophonePermissionsAsync and getMicrophonePermissionsAsync to interact with the permissions.
[PermissionResponse | null, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]Example
const [status, requestPermission] = Camera.useMicrophonePermissions();
Classes
Type: Class extends NativeModule<CameraEvents>
CameraNativeModule Properties
() => Promise<void>Record<keyof FlashMode, CameraNativeProps[flashMode]>() => Promise<VideoCodec[]>() => Promise<PermissionResponse>() => Promise<PermissionResponse>() => Promise<boolean>(options?: ScanningOptions) => Promise<void>() => Promise<PermissionResponse>() => Promise<PermissionResponse>(options?: DocumentScanningOptions) => Promise<DocumentScanningResult | null>(url: string, barcodeTypes?: BarcodeType[]) => Promise<BarcodeScanningResult[]>Record<keyof CameraType, CameraNativeProps[facing]>Type: Class extends SharedRef<'image'>
A reference to a native instance of the image.
PictureRef Properties
PictureRef Methods
Methods
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
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).
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'
Literal type: string
Acceptable values are: 'portrait' | 'portraitUpsideDown' | 'landscapeLeft' | 'landscapeRight'
Literal type: string
Flash mode for the camera.
off- Flash is disabled.on- Flash will fire for every capture.auto- Flash will fire automatically when required.screen- Uses the device screen as a flash for front camera selfies. On Android, this uses CameraX's dedicated screen flash mode. On iOS, this maps to 'on' which triggers Retina Flash automatically.
Acceptable values are: 'off' | 'on' | 'auto' | 'screen'
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
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.
off- No stabilization.standard- Standard stabilization.cinematic- Cinematic stabilization (provides more aggressive stabilization).auto- The system automatically chooses the best stabilization mode.
On Android, standard, cinematic, and auto all enable video stabilization,
while off disables it. The specific stabilization method is determined by the device.
Acceptable values are: 'off' | 'standard' | 'cinematic' | 'auto'
Enums
权限
Android
此软件包会自动将 CAMERA 权限添加到应用中。如果要录制带音频的视频,必须在 app.json 的 expo.android.permissions 数组中包含 RECORD_AUDIO。
iOS
此库使用以下用法描述键: