React Native - 调用摄像头拍照(使用react-native-camera库)
作者:hangge | 2017-04-18 08:10
1,react-native-camera介绍
- react-native-camera 是一个第三方的开源库,我们可以通过它来调用设备的摄像头,从而实现拍照、或者录像功能。
- react-native-camera 功能强大,我们可以选择使用哪个摄像头、是拍照还是录像、是否录制声音、是否开启闪光灯、视图比例、拍摄质量、拍摄方向、触摸功能、条形码/二维码扫描等等。
- GitHub 主页地址:https://github.com/lwansbrough/react-native-camera
2,安装配置
(1)首先在“终端”中进入项目目录,然后执行如下命令安装最新版本的 react-native-camera
npm install react-native-camera@latest --save
(2)接着运行如下命令链接相关的依赖库:
react-native link react-native-camera
(3)由于我们需要调用摄像头拍照,同时拍完还要保存到相册中。因此需要在 Info.plist 配置请求摄像头、及照片相关的描述字段(Privacy - Camera Usage Description、Privacy - Photo Library Usage Description)
如果要拍摄录像的话,还需要加上:Privacy - Microphone Usage Description

(2)样例代码

3,使用样例
(1)效果图
- 程序启动后全屏显示当前摄像头拍摄的图像。
- 默认使用的后置摄像头。点击“切换摄像头”按钮可以在前置、后置摄像头间相互切换。
- 点击拍照,拍摄成功后会自动将照片保存到系统相簿中,并弹出显示照片的路径。


import React, { Component } from 'react';
import {
AppRegistry,
Dimensions,
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
import Camera from 'react-native-camera';
class App extends Component {
//构造函数
constructor(props) {
super(props);
this.state = {
cameraType: Camera.constants.Type.back
};
}
//渲染
render() {
return (
<View style={styles.container}>
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
type={this.state.cameraType}
aspect={Camera.constants.Aspect.fill}>
<Text style={styles.button} onPress={this.switchCamera.bind(this)}>[切换摄像头]</Text>
<Text style={styles.button} onPress={this.takePicture.bind(this)}>[拍照]</Text>
</Camera>
</View>
);
}
//切换前后摄像头
switchCamera() {
var state = this.state;
if(state.cameraType === Camera.constants.Type.back) {
state.cameraType = Camera.constants.Type.front;
}else{
state.cameraType = Camera.constants.Type.back;
}
this.setState(state);
}
//拍摄照片
takePicture() {
this.camera.capture()
.then(function(data){
alert("拍照成功!图片保存地址:\n"+data.path)
})
.catch(err => console.error(err));
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'space-between',
alignItems: 'flex-end',
flexDirection: 'row',
},
toolBar: {
width: 200,
margin: 40,
backgroundColor: '#000000',
justifyContent: 'space-between',
},
button: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40,
}
});
AppRegistry.registerComponent('ReactDemo', () => App);
全部评论(0)