【问题标题】:image not initialized after capture using react native and expo使用 react native 和 expo 捕获后未初始化图像
【发布时间】:2018-12-05 21:26:08
【问题描述】:

我正在尝试在拍摄后显示图像,现在就在相机下方。但是,我拍完图片后,图片变量本身就被初始化为:Promise { "_40": 0,"_55": null,"_65": 0,"_72":null,},而且图片的uri/path都是未定义的。 _maybeRenderImage() 函数旨在仅在从相机初始化后才显示图像。

相机工作正常,我什至看到窗口重新调整了图像的大小,但只有一个白屏而不是图像。我究竟做错了什么?是否与异步调用和takePicture 函数有关?任何帮助表示赞赏!

const StyledCenterView = styled(View)`
  justify-content: center;
  align-items: center;
  flex: 1;
`;

interface CameraState {
  permissionsGranted: boolean;
  image: any;
  type: any;
}

class CameraView extends React.Component<any, CameraState> {
  camera:any = null;

  constructor(props: any) {
    super(props);
    this.state = {
      permissionsGranted: null,
      image: null,
      type: Camera.Constants.Type.back,
    };
  }

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

  takePicture = () => {
    if (this.camera) {
      const photo = this.camera.takePictureAsync();
      console.log(photo.uri);
      console.log(photo.path);
      this.setState({ image: photo });
    }
  }

  _maybeRenderImage = () => {
    const { image } = this.state;
    if (image) {
      console.log('got an image!');
      return <Image
      source={{ uri: image.uri }}
        style={{ width: 250, height: 250 }} />;
    } else {
      console.log('no image in state');
    }
  }

  render() {
    const { permissionsGranted } = this.state;
    if (permissionsGranted === null) {
      return <Text>Access not asked for</Text>;
    } else if (permissionsGranted === false) {
      return <Text>Change permissions to allow camera usage!</Text>;
    } else {
      return(
      <View flex>
        <Camera
          ref={(ref:any) => {
            this.camera = ref;
          }}
          style={{ flex: 1 }}>
        </Camera>
        <TouchableOpacity
          onPress={this.takePicture}
          style={{ alignSelf: 'center' }}>
          <Ionicons name="ios-radio-button-on" size={70} color="black" />
        </TouchableOpacity>

        {this._maybeRenderImage()}

      </View>
      );
    }
  }
}

export default CameraView;

【问题讨论】:

标签: reactjs react-native camera uri expo


【解决方案1】:

我今天遇到了同样的问题,发现了这个问题(通过谷歌搜索我看到的结果值中的值!)。 @Cherniv 的评论是正确的,我将重写它作为完整性的答案(以防他的 jsfiddle 消失)。

takePictureAsync 返回一个 Promise;解决它的最简单方法是使用await,这意味着您还需要将takePicture 函数设为async,如下所示:

takePicture = async () => {   // added "async" here
  if (this.camera) {
    const photo = await this.camera.takePictureAsync(); // added "await" here
    console.log(photo.uri);
    console.log(photo.path);
    this.setState({ image: photo });
  }
}

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 2018-11-21
    • 2019-06-02
    • 2018-09-24
    • 2020-05-12
    相关资源
    最近更新 更多