我正在尝试在拍摄后立即在相机下方显示图像。但是,在拍摄图像后,图像变量本身被初始化为: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;
答案 0 :(得分:0)
我今天遇到了同样的问题,并找到了这个问题(通过谷歌搜索我看到的结果值中的值!)。 @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 });
}
}