如何访问相机 - React Native

时间:2017-07-23 19:27:34

标签: android ios react-native

这应包含在react-native API中,但我似乎无法找到任何包含在内的API。

我想点击按钮打开相机。我可以看到一些仅适用于iOS的API,但本地反应可以使事物跨平台。

有没有人知道如何使用react-native访问相机(而不是图库)?

4 个答案:

答案 0 :(得分:13)

您可能希望使用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);

答案 1 :(得分:0)

我为相机尝试了许多选项,根据我的经验,您可以使用由Wix提供支持的react-native-camera-kit。 这是我的代码

import React from 'react';
import { StyleSheet, Text, View, Alert, ActivityIndicator, PermissionsAndroid } from 'react-native';
import { CameraKitCameraScreen } from 'react-native-camera-kit';

export default class App extends React.Component {
  state = {isPermitted:false}
  constructor(props) {
    super(props);
    var that=this;
    async function requestCameraPermission() {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.CAMERA,{
            'title': 'CameraExample App Camera Permission',
            'message': 'CameraExample App needs access to your camera '
          }
        )
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          requestExternalWritePermission();
        } else {
          alert("CAMERA permission denied");
        }
      } catch (err) {
        alert("Camera permission err",err);
        console.warn(err)
      }
    }
    async function requestExternalWritePermission() {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,{
            'title': 'CameraExample App External Storage Write Permission',
            'message': 'CameraExample App needs access to Storage data in your SD Card '
          }
        )
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          requestExternalReadPermission();
        } else {
          alert("WRITE_EXTERNAL_STORAGE permission denied");
        }
      } catch (err) {
        alert("Write permission err",err);
        console.warn(err)
      }
    }
    async function requestExternalReadPermission() {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,{
            'title': 'CameraExample App Read Storage Write Permission',
            'message': 'CameraExample App needs access to your SD Card '
          }
        )
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          that.setState({isPermitted:true})
        } else {
          alert("READ_EXTERNAL_STORAGE permission denied");
        }
      } catch (err) {
        alert("Read permission err",err);
        console.warn(err)
      }
    }
    requestCameraPermission();
  }

  onBottomButtonPressed(event) {
    const captureImages = JSON.stringify(event.captureImages);
    Alert.alert(
      event.type,
      captureImages,
      [{ text: 'OK', onPress: () => console.log('OK Pressed') }],
      { cancelable: false }
    );
  }

  render() {
    if(this.state.isPermitted){
      return (
        <CameraKitCameraScreen
          actions={{ rightButtonText: 'Done', leftButtonText: 'Cancel' }}
          onBottomButtonPressed={event => this.onBottomButtonPressed(event)}
          flashImages={{
            on: require('./assets/flashon.png'),
            off: require('./assets/flashoff.png'),
            auto: require('./assets/flashauto.png'),
          }}
          cameraFlipImage={require('./assets/flip.png')}
          captureButtonImage={require('./assets/capture.png')}
        />
      );
    }else{
      return (  
        <ActivityIndicator />
      )
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

答案 2 :(得分:0)

我发现 react-native-picker 图像选择器更适合我的需要,它可用于相机和图库。对于下面的示例,您需要安装版本:“react-native-image-picker”:“^3.3.2”,

https://www.npmjs.com/package/react-native-image-picker

import React, {useState, useEffect} from 'react';
import {StyleSheet, Text, View, Image} from 'react-native';
import cameraImage from '../../../../assets/icons/camera.png';
import galleryImage from '../../../../assets/icons//gallery.png';
import {TouchableWithoutFeedback} from 'react-native-gesture-handler';
import * as ImagePicker from 'react-native-image-picker';
import {PermissionsAndroid} from 'react-native';
const ImagePicker = () => {
  const [responseCamera, setResponseCamera] = React.useState(null);
  const [responseGallery, setResponseGallery] = React.useState(null);

  const openCameraWithPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.CAMERA,
        {
          title: 'App Camera Permission',
          message: 'App needs access to your camera ',
          buttonNeutral: 'Ask Me Later',
          buttonNegative: 'Cancel',
          buttonPositive: 'OK',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        ImagePicker.launchCamera(
          {
            mediaType: 'photo',
            includeBase64: false,
            maxHeight: 200,
            maxWidth: 200,
          },
          (response) => {
            console.log(response);
            setResponseCamera(response);
            setResponseGallery(null);
          },
        );
      } else {
        console.log('Camera permission denied');
      }
    } catch (err) {
      console.warn(err);
    }
  };

  return (
    <View
      style={{
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-around',
        margin: 4,
      }}>
      <TouchableOpacity onPress={() => openCameraWithPermission()}>
        {responseCamera === null ? (
          <Image style={styles.icon} source={cameraImage} />
        ) : (
          <Image style={styles.icon} source={{uri: responseCamera.uri}} />
        )}
      </TouchableOpacity>
      <TouchableOpacity
        onPress={() =>
          ImagePicker.launchImageLibrary(
            {
              mediaType: 'photo',
              includeBase64: false,
              maxHeight: 200,
              maxWidth: 200,
            },
            (response) => {
              setResponseGallery(response);
              setResponseCamera(null);
            },
          )
        }>
        {responseGallery === null ? (
          <Image style={styles.icon} source={galleryImage} />
        ) : (
          <Image style={styles.icon} source={{uri: responseGallery.uri}} />
        )}
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  icon: {
    height: 50,
    width: 50,
  },
});

export default ImagePicker;

安卓权限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" />

enter image description here

答案 3 :(得分:-1)

在React Native中,您可以先使用NPM安装摄像头来访问摄像头: npm install react-native-camera --save react-native link react-native-camera

然后在你的组件中使用它:

<samlp:AuthnRequest>

请参阅此github repo以获取完整示例: https://github.com/lwansbrough/react-native-camera