expo-camera로 카메라 접근하기
카메라 권한을 요청하고 셔터 버튼이 있는 Camera 컴포넌트를 렌더링하며 사진을 촬영한 뒤 Image 컴포넌트에 촬영한 이미지 URI를 표시합니다.
expo-camera로 카메라 접근하기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Use expo-camera?
expo-camera provides a React Native component that renders a live camera preview and lets users capture photos and videos. It works in both iOS and Android and integrates cleanly with Expo's managed workflow. Using expo-camera you can build features like profile photo capture, document scanning, QR code reading, and real-time image capture without writing any native code.
Installing expo-camera
Install expo-camera with the Expo install command so Expo picks the SDK-compatible version. After installation, expo-camera's native modules are linked automatically in an Expo managed project. In a bare workflow project you must also run pod install for iOS after installing.
npx expo install expo-cameraRequesting Camera Permission
Before showing the camera, you must request the user's permission. Use Camera.requestCameraPermissionsAsync() and check the returned status field. If the status is not 'granted', the camera cannot be shown. Always request permission in response to a user action (like tapping a button) so the OS permission dialog appears at a natural moment.
import { Camera } from 'expo-camera';
const [permission, requestPermission] = Camera.useCameraPermissions();
if (!permission) {
return <ActivityIndicator />;
}
if (!permission.granted) {
return (
<View>
<Text>Camera access is required to take photos.</Text>
<Button title='Grant Permission' onPress={requestPermission} />
</View>
);
}Rendering the Camera Component
Once permission is granted, render the CameraView component from expo-camera. Give it a style with defined dimensions — it will not render if it has no size. The camera preview fills the allocated space. Use facing to set the initial lens: 'back' for the rear camera or 'front' for the selfie camera.
import { CameraView } from 'expo-camera';
import { StyleSheet } from 'react-native';
export default function CameraScreen() {
const [permission, requestPermission] = Camera.useCameraPermissions();
const cameraRef = React.useRef(null);
if (!permission?.granted) return <PermissionPrompt onPress={requestPermission} />;
return (
<View style={styles.container}>
<CameraView style={styles.camera} facing='back' ref={cameraRef} />
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1 },
camera: { flex: 1 },
});Capturing a Photo
Attach a ref to the CameraView component and call ref.current.takePictureAsync() to capture a photo. This returns a CameraCapturedPicture object with a uri property pointing to the captured image on the device's temporary file system. Display the captured image using React Native's Image component.
const [photo, setPhoto] = React.useState(null);
async function takePicture() {
if (cameraRef.current) {
const captured = await cameraRef.current.takePictureAsync({
quality: 0.8, // 0 to 1, lower = smaller file
base64: false, // true to include base64 string in result
});
setPhoto(captured.uri);
}
}Displaying the Captured Image
Once a photo URI is captured, switch the view from the camera preview to an Image component showing the captured photo. Provide 'Retake' and 'Use Photo' buttons so the user can confirm or discard the capture. This preview-before-confirm pattern is standard in camera apps and prevents accidental bad photos.
if (photo) {
return (
<View style={styles.container}>
<Image source={{ uri: photo }} style={styles.camera} />
<View style={styles.buttonRow}>
<Button title='Retake' onPress={() => setPhoto(null)} />
<Button title='Use Photo' onPress={() => onPhotoSelected(photo)} />
</View>
</View>
);
}Toggling Between Front and Back Camera
Allow users to switch between the front and back camera by toggling a state variable. Pass the state to the facing prop of CameraView. React Native handles the camera switch automatically when the prop changes. Add a flip button in the UI overlay for intuitive UX.
const [facing, setFacing] = React.useState<'back' | 'front'>('back');
function toggleCamera() {
setFacing((current) => (current === 'back' ? 'front' : 'back'));
}
<CameraView style={styles.camera} facing={facing} ref={cameraRef}>
<TouchableOpacity onPress={toggleCamera} style={styles.flipButton}>
<Ionicons name='camera-reverse' size={32} color='white' />
</TouchableOpacity>
<TouchableOpacity onPress={takePicture} style={styles.shutterButton} />
</CameraView>Scanning QR Codes
CameraView also supports barcode scanning, including QR codes. Set the onBarcodeScanned prop to a callback function. The callback fires with a result object containing the barcode type and data (the decoded string). Pause scanning after the first result to avoid handling the same code multiple times.
const [scanned, setScanned] = React.useState(false);
function handleBarcodeScan({ type, data }) {
if (!scanned) {
setScanned(true);
Alert.alert('Scanned!', 'Type: ' + type + '\nData: ' + data, [
{ text: 'Scan Again', onPress: () => setScanned(false) },
]);
}
}
<CameraView
style={styles.camera}
onBarcodeScanned={scanned ? undefined : handleBarcodeScan}
barcodeScannerSettings={{ barcodeTypes: ['qr', 'ean13'] }}
/>Adjusting Camera Quality
The pictureSize prop lets you control the resolution of captured images. Use Camera.getAvailablePictureSizesAsync to query the device's supported sizes and let users choose. Higher resolution photos are better quality but produce larger files. For user-facing profile photos, a medium resolution (around 1080p) is usually the right balance.
const photo = await cameraRef.current.takePictureAsync({
quality: 0.7,
exif: false, // skip EXIF metadata to reduce file size
skipProcessing: true, // faster capture on Android
});
console.log('Photo size:', photo.width, 'x', photo.height);Saving to the Media Library
A captured photo's uri points to a temporary location. To save it permanently to the device's photo gallery, use expo-media-library. Call MediaLibrary.saveToLibraryAsync(photo.uri) after capture. Remember to request MediaLibrary permission separately in addition to the camera permission.
import * as MediaLibrary from 'expo-media-library';
async function savePhoto(uri: string) {
const { status } = await MediaLibrary.requestPermissionsAsync();
if (status === 'granted') {
await MediaLibrary.saveToLibraryAsync(uri);
Alert.alert('Saved!', 'Photo saved to your gallery.');
}
}Camera Overlay UI Tips
The CameraView component can render child components on top of the camera preview, acting as a UI overlay. Place shutter buttons, flash toggles, and crop guides as absolute-positioned children inside CameraView. Use a StyleSheet with position: 'absolute' and bottom / top coordinates to position overlay controls intuitively over the live preview.
Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: Camera.useCameraPermissions handles requesting and checking camera permission before rendering the viewfinder, CameraView with a ref lets you call takePictureAsync to capture a photo and get its URI, and onBarcodeScanned enables QR code reading with the same camera component. Next up we explore reading GPS location with expo-location.
자주 묻는 질문
“expo-camera로 카메라 접근하기” 강의는 무료인가요?
네 — “expo-camera로 카메라 접근하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“expo-camera로 카메라 접근하기”에서 뭘 배우나요?
카메라 권한을 요청하고 셔터 버튼이 있는 Camera 컴포넌트를 렌더링하며 사진을 촬영한 뒤 Image 컴포넌트에 촬영한 이미지 URI를 표시합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
React Native Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“expo-camera로 카메라 접근하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- expo-camera로 카메라 접근하기
- expo-location으로 GPS 위치 읽기
- 로컬 알림 예약하기
- 권한을 적절하게 처리하기