TakePhoto.js
3.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import React, {useEffect, useState, useRef} from 'react';
import * as MediaLibrary from 'expo-media-library';
import * as Permission from 'expo-permissions';
import {Image, ImageBackground, ScrollView, View, Text, TouchableOpacity} from "react-native";
import {useNavigation} from '@react-navigation/native';
import LoadingComponent from "../components/LoadingComponent";
import screen from '../constants/layout';
import { Camera } from 'expo-camera';
import styled from "styled-components";
import {MaterialCommunityIcons} from "@expo/vector-icons";
const TakePhotoButton = styled.TouchableOpacity`
width: 70px;
height: 70px;
border-radius: 50px;
border: 15px solid green;
`;
const TakePhoto = (props) => {
const navigation = useNavigation();
const [loading, setLoading] = useState(false);
const [hasPermission, setHasPermission] = useState(false);
const [cameraType, setCameraType] = useState(Camera.Constants.Type.back);
const [canTakePhoto, setCanTakePhoto] = useState(true);
const cameraRef = useRef(null);
const askPermission = async () => {
try {
setLoading(true);
const {status} = await Permission.askAsync(Permission.CAMERA);
console.log(status);
if (status === 'granted') {
setHasPermission(true);
}
} catch (e) {
console.error(e);
setHasPermission(false);
} finally {
setLoading(false)
}
};
const changeCameraType = () => {
if (cameraType === Camera.Constants.Type.front) {
setCameraType(Camera.Constants.Type.back);
} else {
setCameraType(Camera.Constants.Type.front);
}
};
const takePhoto = async () => {
if (!canTakePhoto) {
return
}
try {
setCanTakePhoto(false);
const {uri} = await cameraRef.current.takePictureAsync({quality: 1});
const asset = await MediaLibrary.createAssetAsync(uri);
navigation.navigate('UploadPhoto', {photo: asset});
} catch (e) {
console.error(e);
setCanTakePhoto(true);
}
};
const goUpload = () => {
navigation.navigate('UploadPhoto');
};
useEffect(() => {
askPermission();
}, []);
return (
<View style={{alignItems: 'center'}}>
{loading
? <LoadingComponent/>
: hasPermission ?
<View>
<Camera
ref={cameraRef}
type={cameraType}
style={{
justifyContent: 'flex-end',
padding: 10,
width: screen.width,
height: screen.height / 2
}}>
<TouchableOpacity onPress={changeCameraType}>
<MaterialCommunityIcons color={'green'} name={'camera'} size={24}/>
</TouchableOpacity>
</Camera>
<TakePhotoButton
onPress={takePhoto}
disabled={!canTakePhoto}
/>
<TakePhotoButton
onPress={goUpload}
/>
</View>
:
null
}
</View>
)
};
export default TakePhoto;