23mofang-react-native-camera 中文文档教程
React Native Camera
React Native 的综合相机模块。 包括照片、视频和条形码扫描!
Contributing
- Pull Requests are welcome, if you open a pull request we will do our best to get to it in a timely manner
- Pull Request Reviews and even more welcome! we need help testing, reviewing, and updating open PRs
- If you are interested in contributing more actively, please contact me (same username on Twitter, Facebook, etc.) Thanks!
- We are now on Open Collective! Contributions are appreciated and will be used to fund core contributors. more details
Breaking Changes
android build tools has been bumped to 25.0.2, please update (can be done via android cli or AndroidStudio)
react-native header imports have changed in v0.40, and that means breaking changes for all! Reference PR & Discussion.
- if on react-native < 0.40:
npm i react-native-camera@0.4
- if on react-native >= 0.40
npm i react-native-camera@0.6
Permissions
要启用视频录制
功能,您必须将以下代码添加到AndroidManifest.xml
:
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
将以下行
Getting started
Requirements
- JDK >= 1.7 (if you run on 1.6 you will get an error on "_cameras = new HashMap<>();")
- With iOS 10 and higher you need to add the "Privacy - Camera Usage Description" key to the info.plist of your project. This should be found in 'yourproject/ios/yourproject/Info.plist'. Add the following code:
<key>NSCameraUsageDescription</key>
<string>Your message to user when the camera is accessed for the first time</string>
<!-- Include this only if you are planning to use the camera roll -->
<key>NSPhotoLibraryUsageDescription</key>
<string>Your message to user when the photo library is accessed for the first time</string>
<!-- Include this only if you are planning to use the microphone for video recording -->
<key>NSMicrophoneUsageDescription</key>
<string>Your message to user when the microsphone is accessed for the first time</string>
- On Android, you require
buildToolsVersion
of25.0.2+
. This should easily and automatically be downloaded by Android Studio's SDK Manager.
Mostly automatic install with react-native
npm install react-native-camera --save
react-native link react-native-camera
Mostly automatic install with CocoaPods
npm install react-native-camera --save
- Add the plugin dependency to your Podfile, pointing at the path where NPM installed it:
pod 'react-native-camera', path: '../node_modules/react-native-camera'
- Run
pod install
Manual install
iOS
npm install react-native-camera --save
- In XCode, in the project navigator, right click
Libraries
➜Add Files to [your project's name]
- Go to
node_modules
➜react-native-camera
and addRCTCamera.xcodeproj
- In XCode, in the project navigator, select your project. Add
libRCTCamera.a
to your project'sBuild Phases
➜Link Binary With Libraries
- Click
RCTCamera.xcodeproj
in the project navigator and go theBuild Settings
tab. Make sure 'All' is toggled on (instead of 'Basic'). In theSearch Paths
section, look forHeader Search Paths
and make sure it contains both$(SRCROOT)/../../react-native/React
and$(SRCROOT)/../../../React
- mark both asrecursive
. - Run your project (
Cmd+R
)
Android
npm install react-native-camera --save
- Open up `android/app/src/main/java/[…]/MainApplication.java
- Add
import com.lwansbrough.RCTCamera.RCTCameraPackage;
to the imports at the top of the file - Add
new RCTCameraPackage()
to the list returned by thegetPackages()
method. Add a comma to the previous item if there's already something there.
附加到
android/settings.gradle
:include ':react-native-camera' project(':react-native-camera').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-camera/android')
将以下行插入到
中的依赖项块中>android/app/build.gradle
:compile project(':react-native-camera')
在您的 Android Manifest 中声明权限(
视频录制
功能需要)
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Usage
您只需要要求
react-native-camera
模块然后使用
标签。
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Dimensions,
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
import Camera from 'react-native-camera';
class BadInstagramCloneApp extends Component {
render() {
return (
<View style={styles.container}>
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
</Camera>
</View>
);
}
takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
.then((data) => console.log(data))
.catch(err => console.error(err));
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});
AppRegistry.registerComponent('BadInstagramCloneApp', () => BadInstagramCloneApp);
Properties
aspect
值:Camera.constants.Aspect.fit
或 "fit"
、Camera.constants.Aspect.fill
或 "fill"< /code>(默认),
Camera.constants.Aspect.stretch
或 "stretch"
aspect
属性允许您定义取景器的呈现方式相机的视图。 例如,如果您有一个方形取景器并且您想要完全填充它,您有两个选项:“填充”
,其中相机视图的纵横比通过裁剪视图或 < code>“stretch”,其中纵横比被倾斜以适合取景器内的整个图像。 另一个选项是 “fit”
,它确保相机的整个视图适合您的取景器,而不会改变纵横比。
iOS
audio
值:true
(布尔值)、false
(默认值)
仅适用于视频捕获模式。 指定音频是否应与视频一起捕获.
captureMode
值:Camera.constants.CaptureMode.still
(默认),Camera.constants.CaptureMode.video
相机将执行的捕获类型 - 静止图像或视频。
captureTarget
值:Camera.constants.CaptureTarget.cameraRoll
(默认),Camera.constants.CaptureTarget.disk
,Camera.constants.CaptureTarget.temp
, ~~Camera.constants.CaptureTarget.memory
~~(已弃用),
此属性允许您指定捕获的图像数据的目标输出。 磁盘输出已显示可以改善捕获响应时间,因此这是推荐值。 使用已弃用的内存输出时,图像二进制文件将作为 base64 编码的字符串发回。
captureQuality
值:Camera.constants.CaptureQuality.high
或 "high"
(默认),Camera.constants.CaptureQuality.medium
或 " medium"
, Camera.constants.CaptureQuality.low
或 "low"
, Camera.constants.CaptureQuality.photo
或 “照片”
、Camera.constants.CaptureQuality["1080p"]
或 "1080p"
、Camera.constants.CaptureQuality["720p" ]
或 "720p"
,Camera.constants.CaptureQuality["480p"]
或 "480p"
。
此属性允许您指定捕获的图像或视频的质量输出。 默认情况下,质量设置为高。
选择更具体的质量设置(1080p、720p、480p)时,请注意每个平台和设备支持不同的有效图片/视频尺寸,并且每个质量设置中的实际分辨率可能不同。 iOS 不应该有太多差异(如果有的话); 1080p 应为 1920x1080,720p 应为 1280x720,480p 应为 640x480(请注意,因此 iOS 480p 不是典型的 16:9 高清纵横比,典型的高清摄像头预览屏幕在纵横比上可能与您实际录制的画面有很大差异!!). 对于 Android,预计会有更多差异:在大多数 Android 上,1080p 应该 提供 1920x1080 而 720p 应该 提供 1280x720; 但是,480p 将“最佳”为 853x480(16:9 高清宽高比),但会回退/下降到 800x480、720x480 或“更差”,具体取决于最接近但低于 853x480 的分辨率以及可在实际设备。 如果您的应用程序需要知道输出图像/视频的精确分辨率,您可以考虑在捕获完成后手动确定实际分辨率(特别是 Android 上的 480p)。
Android 还支持 Camera.constants.CaptureQuality.preview
或 "preview"
将输出图像与预览
type
值中使用的相同图像相匹配:Camera.constants。 Type.front
或 "front"
,Camera.constants.Type.back
或 "back"
(默认)
使用 < code>type 属性来指定要使用的相机。
orientation
价值观: Camera.constants.Orientation.auto
或 "auto"
(默认), Camera.constants.Orientation.landscapeLeft
或 "landscapeLeft"
, Camera.constants.Orientation.landscapeRight
或 "landscapeRight"
,Camera.constants.Orientation.portrait
或 "portrait"
,Camera.constants.Orientation.portraitUpsideDown
或 "portraitUpsideDown"< /code>
orientation
属性允许您指定手机的当前方向以确保取景器“朝上”。
Android
playSoundOnCapture
值:true
(默认值)或 false
此属性允许您指定是否在捕获时播放快门声音。 目前仅适用于 android,等待 合理的静音实现< /a> 在 iOS 中。
onBarCodeRead
当在相机视图中检测到条形码时,将调用指定的方法。
事件包含data
(条码中的数据)和bounds
(勾勒条码的矩形)
。可以识别以下条码类型
aztec
code128
code39
code39mod43
code93
ean13
ean8
pdf417
qr
upce
interleaved2of5
(when available)itf14
(when available)datamatrix
(when available)
: <代码>数据对象。
barCodeTypes
要搜索的一组条形码类型。 默认为上面列出的所有类型。 如果 onBarCodeRead
未定义则无效。
flashMode
价值观: Camera.constants.FlashMode.on
, Camera.constants.FlashMode.off
, Camera.constants.FlashMode.auto
使用 flashMode
属性指定相机闪光灯模式。
torchMode
价值观: Camera.constants.TorchMode.on
, Camera.constants.TorchMode.off
, Camera.constants.TorchMode.auto
使用 torchMode
属性指定相机手电筒模式。
iOS
onFocusChanged: Event { nativeEvent: { touchPoint: { x, y } }
iOS:在做出触摸焦点手势时调用。 默认情况下,未定义 onFocusChanged
并且禁用点击对焦。
Android:这个回调还没有实现。 然而,安卓将 如果设备支持自动对焦,则自动进行点击对焦; 有 目前没有办法从 javascript 管理它。
iOS
defaultOnFocusComponent
价值观: <代码>真(默认) false
如果 defaultOnFocusComponent
设置为 false,将禁用点击对焦手势的视觉反馈的默认内部实现。
iOS
onZoomChanged: Event { nativeEvent: { velocity, zoomFactor } }
iOS:焦点改变时调用。 默认情况下,未定义 onZoomChanged
并且禁用双指缩放。
Android:这个回调还没有实现。 然而,安卓将 自动处理双指缩放; 目前没有办法管理这个 来自javascript。
iOS
keepAwake
如果设置为 true
,当相机预览可见时设备将不会休眠。 这模仿了默认相机应用程序的行为,使设备在打开时保持唤醒状态。
mirrorImage
如果设置为 true
,则返回的图像将被镜像。
fixOrientation
(deprecated)
如果设置为 true
,则返回的图像将旋转到正确的方向。 警告:它使用大量内存,如果设备无法提供足够的 RAM 来执行旋转,我会导致您的应用程序崩溃。
(如果您发现需要使用此选项,因为默认情况下您的图像方向不正确, 可以请提交 PR 并包括设备的品牌型号。 我们相信这不是 不再需要功能并希望将其删除。)
Component instance methods
您可以通过添加 ref
(即 ref="camera"
)属性来访问组件方法你的
元素,然后你可以在你的组件中使用 this.refs.camera.capture(cb)
等。
capture([options]): Promise
从相机捕获数据。 捕获的内容基于 captureMode
和 captureTarget
属性。 captureMode
告诉相机您想要静止图像还是视频。 captureTarget
允许您指定希望如何捕获数据并将其发送回给您。 请参阅属性下的 captureTarget
以查看可用值。
支持的选项:
audio
(SeecaptureAudio
under Properties)mode
(SeecaptureMode
under Properties)target
(SeecaptureTarget
under Properties)metadata
This is metadata to be added to the captured image.location
This is the object returned fromnavigator.geolocation.getCurrentPosition()
(React Native's geolocation polyfill). It will add GPS metadata to the image.rotation
This will rotate the image by the number of degrees specified.jpegQuality
(integer between 1 and 100) This property is used to compress the output jpeg file with 100% meaning no jpeg compression will be applied.totalSeconds
This will limit video length by number of seconds specified. Only works in video capture mode.
承诺将通过具有以下某些属性的对象来实现:
data
: Returns a base64-encoded string with the capture data (only returned with the deprecatedCamera.constants.CaptureTarget.memory
)path
: Returns the path of the captured image or video file on diskwidth
: (currently iOS video only) returns the video file's frame widthheight
: (currently iOS video only) returns the video file's frame heightduration
: (currently iOS video only) video file durationsize
: (currently iOS video only) video file size (in bytes)
iOS
getFOV(): Promise
返回相机的当前视野。
hasFlash(): Promise
返回相机是否具有闪光灯功能。
stopCapture()
结束视频捕获的当前捕获会话。 仅在当前 captureMode
为 video
时适用。
Component static methods
iOS
Camera.checkDeviceAuthorizationStatus(): Promise
公开本机 API 以检查设备是否已授权访问相机(相机和麦克风权限)。 可用于在加载相机组件之前调用以确保正确的用户体验。 根据设备是否获得授权,承诺将以 true
或 false
实现。 请注意,自 iOS 10 起< /a>,您需要将 NSCameraUsageDescription
和 NSMicrophoneUsageDescription
添加到您的 XCode 项目的 Info.plist 文件中,否则您可能会遇到崩溃。
iOS
Camera.checkVideoAuthorizationStatus(): Promise
与 Camera.checkDeviceAuthorizationStatus()
相同,但仅检查相机权限。 请注意,从 iOS 10 开始,您需要将 NSCameraUsageDescription
添加到您的 XCode 项目的 Info.plist 文件中,否则您可能会遇到崩溃。
iOS
Camera.checkAudioAuthorizationStatus(): Promise
与 Camera.checkDeviceAuthorizationStatus()
相同,但仅检查麦克风权限。 请注意,从 iOS 10 开始,您需要将 NSMicrophoneUsageDescription
添加到 XCode 项目的 Info.plist 文件中,否则您可能会遇到崩溃。
Subviews
这个组件支持子视图,所以如果你想使用相机视图作为背景或者如果你想布局按钮/图像/等等。 在相机内部然后你可以做到这一点。
Example
要查看更多 react-native-camera
的操作,您可以在 Example 文件夹。
Open Collective
我们刚刚开始为 react-native-camera 筹资。 非常感谢您的贡献。 当我们获得超过 250 美元时,我们将开始以完全透明的方式向核心维护者分配资金。 欢迎对此过程提供反馈,随着我们的成长和了解更多,我们将继续改进该策略。
Backers
支持我们每月捐款并帮助我们继续我们的活动。 [成为支持者]
Sponsors
成为赞助商并在 Github 上的自述文件中获取您的徽标以及指向您网站的链接。 [成为赞助商]
感谢 Brent Vatne (@brentvatne) 提供的 react-native-video
模块,它为我提供了一个如何设置该模块的好例子.
React Native Camera
The comprehensive camera module for React Native. Including photographs, videos, and barcode scanning!
Contributing
- Pull Requests are welcome, if you open a pull request we will do our best to get to it in a timely manner
- Pull Request Reviews and even more welcome! we need help testing, reviewing, and updating open PRs
- If you are interested in contributing more actively, please contact me (same username on Twitter, Facebook, etc.) Thanks!
- We are now on Open Collective! Contributions are appreciated and will be used to fund core contributors. more details
Breaking Changes
android build tools has been bumped to 25.0.2, please update (can be done via android cli or AndroidStudio)
react-native header imports have changed in v0.40, and that means breaking changes for all! Reference PR & Discussion.
- if on react-native < 0.40:
npm i react-native-camera@0.4
- if on react-native >= 0.40
npm i react-native-camera@0.6
Permissions
To enable video recording
feature you have to add the following code to the AndroidManifest.xml
:
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Getting started
Requirements
- JDK >= 1.7 (if you run on 1.6 you will get an error on "_cameras = new HashMap<>();")
- With iOS 10 and higher you need to add the "Privacy - Camera Usage Description" key to the info.plist of your project. This should be found in 'yourproject/ios/yourproject/Info.plist'. Add the following code:
<key>NSCameraUsageDescription</key>
<string>Your message to user when the camera is accessed for the first time</string>
<!-- Include this only if you are planning to use the camera roll -->
<key>NSPhotoLibraryUsageDescription</key>
<string>Your message to user when the photo library is accessed for the first time</string>
<!-- Include this only if you are planning to use the microphone for video recording -->
<key>NSMicrophoneUsageDescription</key>
<string>Your message to user when the microsphone is accessed for the first time</string>
- On Android, you require
buildToolsVersion
of25.0.2+
. This should easily and automatically be downloaded by Android Studio's SDK Manager.
Mostly automatic install with react-native
npm install react-native-camera --save
react-native link react-native-camera
Mostly automatic install with CocoaPods
npm install react-native-camera --save
- Add the plugin dependency to your Podfile, pointing at the path where NPM installed it:
pod 'react-native-camera', path: '../node_modules/react-native-camera'
- Run
pod install
Manual install
iOS
npm install react-native-camera --save
- In XCode, in the project navigator, right click
Libraries
➜Add Files to [your project's name]
- Go to
node_modules
➜react-native-camera
and addRCTCamera.xcodeproj
- In XCode, in the project navigator, select your project. Add
libRCTCamera.a
to your project'sBuild Phases
➜Link Binary With Libraries
- Click
RCTCamera.xcodeproj
in the project navigator and go theBuild Settings
tab. Make sure 'All' is toggled on (instead of 'Basic'). In theSearch Paths
section, look forHeader Search Paths
and make sure it contains both$(SRCROOT)/../../react-native/React
and$(SRCROOT)/../../../React
- mark both asrecursive
. - Run your project (
Cmd+R
)
Android
npm install react-native-camera --save
- Open up `android/app/src/main/java/[…]/MainApplication.java
- Add
import com.lwansbrough.RCTCamera.RCTCameraPackage;
to the imports at the top of the file - Add
new RCTCameraPackage()
to the list returned by thegetPackages()
method. Add a comma to the previous item if there's already something there.
Append the following lines to
android/settings.gradle
:include ':react-native-camera' project(':react-native-camera').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-camera/android')
Insert the following lines inside the dependencies block in
android/app/build.gradle
:compile project(':react-native-camera')
Declare the permissions in your Android Manifest (required for
video recording
feature)
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Usage
All you need is to require
the react-native-camera
module and then use the <Camera/>
tag.
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Dimensions,
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
import Camera from 'react-native-camera';
class BadInstagramCloneApp extends Component {
render() {
return (
<View style={styles.container}>
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
</Camera>
</View>
);
}
takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
.then((data) => console.log(data))
.catch(err => console.error(err));
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});
AppRegistry.registerComponent('BadInstagramCloneApp', () => BadInstagramCloneApp);
Properties
aspect
Values: Camera.constants.Aspect.fit
or "fit"
, Camera.constants.Aspect.fill
or "fill"
(default), Camera.constants.Aspect.stretch
or "stretch"
The aspect
property allows you to define how your viewfinder renders the camera's view. For instance, if you have a square viewfinder and you want to fill the it entirely, you have two options: "fill"
, where the aspect ratio of the camera's view is preserved by cropping the view or "stretch"
, where the aspect ratio is skewed in order to fit the entire image inside the viewfinder. The other option is "fit"
, which ensures the camera's entire view fits inside your viewfinder without altering the aspect ratio.
iOS
audio
Values: true
(Boolean), false
(default)
Applies to video capture mode only. Specifies whether or not audio should be captured with the video.
captureMode
Values: Camera.constants.CaptureMode.still
(default), Camera.constants.CaptureMode.video
The type of capture that will be performed by the camera - either a still image or video.
captureTarget
Values: Camera.constants.CaptureTarget.cameraRoll
(default), Camera.constants.CaptureTarget.disk
, Camera.constants.CaptureTarget.temp
, ~~Camera.constants.CaptureTarget.memory
~~ (deprecated),
This property allows you to specify the target output of the captured image data. The disk output has been shown to improve capture response time, so that is the recommended value. When using the deprecated memory output, the image binary is sent back as a base64-encoded string.
captureQuality
Values: Camera.constants.CaptureQuality.high
or "high"
(default), Camera.constants.CaptureQuality.medium
or "medium"
, Camera.constants.CaptureQuality.low
or "low"
, Camera.constants.CaptureQuality.photo
or "photo"
, Camera.constants.CaptureQuality["1080p"]
or "1080p"
, Camera.constants.CaptureQuality["720p"]
or "720p"
, Camera.constants.CaptureQuality["480p"]
or "480p"
.
This property allows you to specify the quality output of the captured image or video. By default the quality is set to high.
When choosing more-specific quality settings (1080p, 720p, 480p), note that each platform and device supports different valid picture/video sizes, and actual resolution within each of these quality settings might differ. There should not be too much variance (if any) for iOS; 1080p should give 1920x1080, 720p should give 1280x720, and 480p should give 640x480 (note that iOS 480p therefore is NOT the typical 16:9 HD aspect ratio, and the typically-HD camera preview screen may differ greatly in aspect from what you actually record!!). For Android, expect more variance: on most Androids, 1080p should give 1920x1080 and 720p should give 1280x720; however, 480p will at "best" be 853x480 (16:9 HD aspect ratio), but falls back/down to 800x480, 720x480, or "worse", depending on what is closest-but-less-than 853x480 and available on the actual device. If your application requires knowledge of the precise resolution of the output image/video, you might consider manually determine the actual resolution itself after capture has completed (particularly for 480p on Android).
Android also supports Camera.constants.CaptureQuality.preview
or "preview"
which matches the output image to the same one used in the preview
type
Values: Camera.constants.Type.front
or "front"
, Camera.constants.Type.back
or "back"
(default)
Use the type
property to specify which camera to use.
orientation
Values: Camera.constants.Orientation.auto
or "auto"
(default), Camera.constants.Orientation.landscapeLeft
or "landscapeLeft"
, Camera.constants.Orientation.landscapeRight
or "landscapeRight"
, Camera.constants.Orientation.portrait
or "portrait"
, Camera.constants.Orientation.portraitUpsideDown
or "portraitUpsideDown"
The orientation
property allows you to specify the current orientation of the phone to ensure the viewfinder is "the right way up."
Android
playSoundOnCapture
Values: true
(default) or false
This property allows you to specify whether a shutter sound is played on capture. It is currently android only, pending a reasonable mute implementation in iOS.
onBarCodeRead
Will call the specified method when a barcode is detected in the camera's view.
Event contains data
(the data in the barcode) and bounds
(the rectangle which outlines the barcode.)
The following barcode types can be recognised:
aztec
code128
code39
code39mod43
code93
ean13
ean8
pdf417
qr
upce
interleaved2of5
(when available)itf14
(when available)datamatrix
(when available)
The barcode type is provided in the data
object.
barCodeTypes
An array of barcode types to search for. Defaults to all types listed above. No effect if onBarCodeRead
is undefined.
flashMode
Values: Camera.constants.FlashMode.on
, Camera.constants.FlashMode.off
, Camera.constants.FlashMode.auto
Use the flashMode
property to specify the camera flash mode.
torchMode
Values: Camera.constants.TorchMode.on
, Camera.constants.TorchMode.off
, Camera.constants.TorchMode.auto
Use the torchMode
property to specify the camera torch mode.
iOS
onFocusChanged: Event { nativeEvent: { touchPoint: { x, y } }
iOS: Called when a touch focus gesture has been made. By default, onFocusChanged
is not defined and tap-to-focus is disabled.
Android: This callback is not yet implemented. However, Android will automatically do tap-to-focus if the device supports auto-focus; there is currently no way to manage this from javascript.
iOS
defaultOnFocusComponent
Values: true
(default) false
If defaultOnFocusComponent
set to false, default internal implementation of visual feedback for tap-to-focus gesture will be disabled.
iOS
onZoomChanged: Event { nativeEvent: { velocity, zoomFactor } }
iOS: Called when focus has changed. By default, onZoomChanged
is not defined and pinch-to-zoom is disabled.
Android: This callback is not yet implemented. However, Android will automatically handle pinch-to-zoom; there is currently no way to manage this from javascript.
iOS
keepAwake
If set to true
, the device will not sleep while the camera preview is visible. This mimics the behavior of the default camera app, which keeps the device awake while open.
mirrorImage
If set to true
, the image returned will be mirrored.
fixOrientation
(deprecated)
If set to true
, the image returned will be rotated to the right way up. WARNING: It uses a significant amount of memory and my cause your application to crash if the device cannot provide enough RAM to perform the rotation.
(If you find that you need to use this option because your images are incorrectly oriented by default, could please submit a PR and include the make model of the device. We believe that it's not required functionality any more and would like to remove it.)
Component instance methods
You can access component methods by adding a ref
(ie. ref="camera"
) prop to your <Camera>
element, then you can use this.refs.camera.capture(cb)
, etc. inside your component.
capture([options]): Promise
Captures data from the camera. What is captured is based on the captureMode
and captureTarget
props. captureMode
tells the camera whether you want a still image or video. captureTarget
allows you to specify how you want the data to be captured and sent back to you. See captureTarget
under Properties to see the available values.
Supported options:
audio
(SeecaptureAudio
under Properties)mode
(SeecaptureMode
under Properties)target
(SeecaptureTarget
under Properties)metadata
This is metadata to be added to the captured image.location
This is the object returned fromnavigator.geolocation.getCurrentPosition()
(React Native's geolocation polyfill). It will add GPS metadata to the image.rotation
This will rotate the image by the number of degrees specified.jpegQuality
(integer between 1 and 100) This property is used to compress the output jpeg file with 100% meaning no jpeg compression will be applied.totalSeconds
This will limit video length by number of seconds specified. Only works in video capture mode.
The promise will be fulfilled with an object with some of the following properties:
data
: Returns a base64-encoded string with the capture data (only returned with the deprecatedCamera.constants.CaptureTarget.memory
)path
: Returns the path of the captured image or video file on diskwidth
: (currently iOS video only) returns the video file's frame widthheight
: (currently iOS video only) returns the video file's frame heightduration
: (currently iOS video only) video file durationsize
: (currently iOS video only) video file size (in bytes)
iOS
getFOV(): Promise
Returns the camera's current field of view.
hasFlash(): Promise
Returns whether or not the camera has flash capabilities.
stopCapture()
Ends the current capture session for video captures. Only applies when the current captureMode
is video
.
Component static methods
iOS
Camera.checkDeviceAuthorizationStatus(): Promise
Exposes the native API for checking if the device has authorized access to the camera (camera and microphone permissions). Can be used to call before loading the Camera component to ensure proper UX. The promise will be fulfilled with true
or false
depending on whether the device is authorized. Note, as of iOS 10, you will need to add NSCameraUsageDescription
and NSMicrophoneUsageDescription
to your XCode project's Info.plist file or you might experience a crash.
iOS
Camera.checkVideoAuthorizationStatus(): Promise
The same as Camera.checkDeviceAuthorizationStatus()
but only checks the camera permission. Note, as of iOS 10, you will need to add NSCameraUsageDescription
to your XCode project's Info.plist file or you might experience a crash.
iOS
Camera.checkAudioAuthorizationStatus(): Promise
The same as Camera.checkDeviceAuthorizationStatus()
but only checks the microphone permission. Note, as of iOS 10, you will need to add NSMicrophoneUsageDescription
to your XCode project's Info.plist file or you might experience a crash.
Subviews
This component supports subviews, so if you wish to use the camera view as a background or if you want to layout buttons/images/etc. inside the camera then you can do that.
Example
To see more of the react-native-camera
in action, you can check out the source in Example folder.
Open Collective
We are just beginning a funding campaign for react-native-camera. Contributions are greatly appreciated. When we gain more than $250 we will begin distributing funds to core maintainers in a fully transparent manner. Feedback for this process is welcomed, we will continue to evolve the strategy as we grow and learn more.
Backers
Support us with a monthly donation and help us continue our activities. [Become a backer]
Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [Become a sponsor]
Thanks to Brent Vatne (@brentvatne) for the react-native-video
module which provided me with a great example of how to set up this module.