September 01, 2019
해당 포스트는 Nomad Coder의 초보를 위한 RN강의를 정리한 내용입니다.
componentDidMount 수정하기지금까지 카메라 권한을 얻고 카메라를 띄우는 것까지 진행하였고
이번 포스트에는 전방/후방 카메라를 변경하는 방법에 대해 설명해보겠습니다.
카메라의 타입은 Camera컴포넌트에 type을 속성으로 주면된다.
카메라의 속성은 Camera의 Constants안에 정의 되어있다.
<Camera
style={{
width: width - 40,
height: height / 1.5,
borderRadius: 10,
overflow: 'hidden',
}}
type={Camera.Constants.Type.front}
/>기본값은 Type.back이고 Type.front를 사용하면 전방 카메라가 켜진다.
위와 같이 코드를 변경해주고 전방 카메라가 켜지는지 테스트해보자.
전방 카메라로 잘 작동하는 것을 확인할 수 있다.
우리 앱의 cameraType의 기본 값은 전면 카메라로 설정해 사용하겠습니다.
Camera 컴포넌트에 type에 cameraType을 전달합니다.
state = {
hasPermission: null,
cameraType: Camera.Constants.Type.front
};
...
<Camera
style={{
width: width - 40,
height: height / 1.5,
borderRadius: 10,
overflow: "hidden"
}}
type={cameraType}
/>...
import { MaterialIcons } from "@expo/vector-icons";
...<MaterialIcons
name={
cameraType === Camera.Constants.Type.front ? 'camera-rear' : 'camera-front'
}
size={44}
color="white"
/>아래와 같이 IconBar를 작성하고 MaterialIcons를 감싸줍니다.
const IconBar = styled.View`
margin-top: 40px;
`;
...
<IconBar>
<MaterialIcons
...
/>
</IconBar>state를 Camera.Constants.Type.front와 Camera.Constants.Type.back으로
바꾸면서 화면과 아이콘의 변화를 테스트합니다.
state에 따라 화면이 변화하는 것을 확인할 수 있습니다.
이제 버튼을 클릭하면 state를 변경하도록 하는 함수를 작성하겠습니다.
react-native의 TouchableOpacity를 추가합니다.
import { ActivityIndicator, Dimensions, TouchableOpacity } from 'react-native'<TouchableOpacity>
<MaterialIcons
name={
cameraType === Camera.Constants.Type.front
? 'camera-rear'
: 'camera-front'
}
size={44}
color="white"
/>
</TouchableOpacity>cameraType을 front일 경우 back으로 back일 경우 front로
this.setState 함수를 사용해 변경해준다.
switchCameraType = () => {
const { cameraType } = this.state
if (cameraType === Camera.Constants.Type.front) {
this.setState({
cameraType: Camera.Constants.Type.back,
})
} else {
this.setState({
cameraType: Camera.Constants.Type.front,
})
}
}작성한 swithCameraType함수를 onPress속성에 전달한다.
<TouchableOpacity onPress={this.switchCameraType}>
<MaterialIcons
name={
cameraType === Camera.Constants.Type.front
? 'camera-rear'
: 'camera-front'
}
size={44}
color="white"
/>
</TouchableOpacity>아래와 같이 잘 작동하는 것을 확인할 수 있다.

다음 포스트에서는 얼굴을 인식하고 직접 사진을 찍는 것 까지 진행해보겠습니다.