如何使用EXPO React Native相机拍摄照片?

时间:2018-10-08 17:03:11

标签: react-native expo react-native-camera

我刚开始在Expo上使用React Native,所以我有点困惑。因此,我制作了一个相机组件,并将其导入了主屏幕。一切看起来都很好。但是我不能拍照。我无法单击捕捉图标并保存图像。有没有我错过的组件? 我只在下面发布了CameraComponent类。

Camera.js

class CameraComponent extends Component {

  state = {
    hasCameraPermission: null,
    type: Camera.Constants.Type.back
  }

  async componentWillMount() {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({ hasCameraPermission: status === 'granted' })
  }

  render() {
    const { hasCameraPermission } = this.state

    if (hasCameraPermission === null) {
      return <View />
    }
    else if (hasCameraPermission === false) {
      return <Text> No access to camera</Text>
    }
    else {
      return (
        <View style={{ flex: 1 }}>
          <Camera 
            style={{ flex: 1, justifyContent: 'space-between' }}
            type={this.state.type}
          >
            <Header
              searchBar
              rounded
              style={{
                position: 'absolute',
                backgroundColor: 'transparent',
                left: 0,
                top: 0,
                right: 0,
                zIndex: 100,
                alignItems: 'center'
              }}
            >
              <View style={{ flexDirection: 'row', flex: 4 }}>
                <Ionicons name="md-camera" style={{ color: 'white' }} />
                <Item style={{ backgroundColor: 'transparent' }}>
                  <Icon name="ios-search" style={{ color: 'white', fontSize: 24, fontWeight: 'bold' }}></Icon>
                </Item>
              </View>

              <View style={{ flexDirection: 'row', flex: 2, justifyContent: 'space-around' }}>
                <Icon name="ios-flash" style={{ color: 'white', fontWeight: 'bold' }} />
                <Icon
                  onPress={() => {
                    this.setState({
                      type: this.state.type === Camera.Constants.Type.back ?                                        
                                            Camera.Constants.Type.front :
                                            Camera.Constants.Type.back
                    })
                  }}
                  name="ios-reverse-camera"
                  style={{ color: 'white', fontWeight: 'bold' }}
                />
              </View>
            </Header>

            <View style={{ flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 30, marginBottom: 15, alignItems: 'flex-end' }}>
              <Ionicons name="ios-map" style={{ color: 'white', fontSize: 36 }}></Ionicons>
              <View></View>
              <View style={{ alignItems: 'center' }}>
                <MaterialCommunityIcons name="circle-outline"   // This is the icon which should take and save image
                  style={{ color: 'white', fontSize: 100 }}
                ></MaterialCommunityIcons>
                <Icon name="ios-images" style={{ color: 'white', fontSize: 36 }} />
              </View>
            </View>
          </Camera>
        </View>
      )
    }
  }
}

export default CameraComponent;

位于中心的图标(即圆圈图标)应自动拍摄并保存图像。

5 个答案:

答案 0 :(得分:2)

因此,您需要告诉“圆圈图标”才能拍照。首先,我会像这样为您的相机添加参考

<Camera style={{ flex: 1 }}
      ref={ (ref) => {this.camera = ref} }
      type={this.state.type}>

然后创建一个实际上告诉您的应用拍照的功能:

 async snapPhoto() {       
    console.log('Button Pressed');
    if (this.camera) {
       console.log('Taking photo');
       const options = { quality: 1, base64: true, fixOrientation: true, 
       exif: true};
       await this.camera.takePictureAsync(options).then(photo => {
          photo.exif.Orientation = 1;            
           console.log(photo);            
           });     
     }
    }

现在使图标具有onPress()来拍照。我做了这样的事情。

<TouchableOpacity style={styles.captureButton} onPress={this.snapPhoto.bind(this)}>
                <Image style={{width: 100, height: 100}} source={require('../assets/capture.png')}          
                />
            </TouchableOpacity>

您可能还想创建一个呈现图像预览或类似内容的视图。世博文档中有一个很好的入门示例。请注意,Expo创建了一个名为“ Camera”的缓存文件夹,该文件夹最初是图像。

答案 1 :(得分:2)

您也可以在功能组件中使用通过React Hook创建的引用来执行此操作。这是一个基于expo SDK 38 Camera组件https://docs.expo.io/versions/v38.0.0/sdk/camera/

的示例
import React, { useState, useEffect, useRef } from 'react';
import { Text, View, TouchableOpacity } from 'react-native';
import { Camera } from 'expo-camera';

export default function App() {
  const [hasPermission, setHasPermission] = useState(null);
  const [type, setType] = useState(Camera.Constants.Type.back);
  const ref = useRef(null)

  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);
  
  _takePhoto = async () => {
    const photo = await ref.current.takePictureAsync()
    console.debug(photo)
  }

  if (hasPermission === null) {
    return <View />;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }
  return (
    <View style={{ flex: 1 }}>
      <Camera style={{ flex: 1 }} type={type} ref={ref}>
        <View
          style={{
            flex: 1,
            backgroundColor: 'transparent',
            flexDirection: 'row',
          }}>
          <TouchableOpacity
            style={{
              flex: 0.1,
              alignSelf: 'flex-end',
              alignItems: 'center',
            }}
            onPress={() => {
              setType(
                type === Camera.Constants.Type.back
                  ? Camera.Constants.Type.front
                  : Camera.Constants.Type.back
              );
            }}>
            <Text style={{ fontSize: 18, marginBottom: 10, color: 'white' }}> Flip </Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={_takePhoto}
          >
            <Text>Snap Photo</Text>
          </TouchableOpacity>
        </View>
      </Camera>
    </View>
  );
}

我没有检查该UI的外观,但重点是利用React.useRef并将引用附加到您的<Camera/>组件。然后,您可以调用ref.current.takePictureAsync来捕获和访问新图像。请在下面查看与捕捉照片有关的重要片段。

import React from 'react'
/* ... other imports
*/

export default CameraScene = () => {
  /* ... other state and permission logic
  */
  const ref = useRef(null)
  const _takePhoto = async () => {
    const photo = await ref.current.takePictureAsync()
    console.debug(photo)
  }
  return (
    <Camera style={{flex: 1}} ref={ref}> /* ...
    ... other ui logic
    */
    </Camera>
  ) 
}

https://reactjs.org/docs/hooks-reference.html#useref处了解有关useRef的更多信息

答案 2 :(得分:1)

当异步takePictureAsync函数返回时,您可以使用“ onPictureSaved”,以便抓取照片对象:

  takePicture = () => {
      if (this.camera) {
          this.camera.takePictureAsync({ onPictureSaved: this.onPictureSaved });
      }
   };

  onPictureSaved = photo => {
      console.log(photo);
  } 

在视图中,您将有一个带参考的Camera组件:

<Camera style={styles.camera} type={this.state.type} ref={(ref) => { this.camera = ref }} >

还有一个在按下时将调用takePicture函数的按钮:

<TouchableOpacity style={styles.captureButton} onPress={this.takePicture} />

答案 3 :(得分:0)

您是否要在实际的物理设备上执行此操作?您无法使用模拟器拍摄图片。

答案 4 :(得分:0)

您需要在Camera类中添加一个引用,才能在您自己的“ handle”方法中调用它的takePictureAsync函数。

cameraRef = React.createRef();

<Camera ref={this.cameraRef}>...</Camera>

调用引用的摄像机的方法时不要忘记“ .current”。

handlePhoto = async () => {
  if(this.cameraRef){
    let photo = await this.cameraRef.current.takePictureAsync();
    console.log(photo);
  }  
}

然后只需在充当可照片捕捉按钮的可触摸元素上调用您的“处理”方法即可。

<TouchableOpacity 
  style={{width:60, height:60, borderRadius:30, backgroundColor:"#fff"}} 
  onPress={this.takePhoto} />

您应该能够在控制台中看到记录的照片。