Kā izveidot kameras lietotni ar Expo un React Native
Ja neesat pazīstams ar ekspozīciju, tas ir klients, kas palīdz jums izveidot React Native lietotnes ar mazāku sarežģītības pakāpi. Tas arī palīdz jums tikt galā ar stresu, ko rada vides uzstādīšana un iestatīšana, lai palaistu React Native.
Šajā apmācībā mēs izveidosim vienkāršu kameras lietotni, kurā lietotājs var fotografēt, skatīt savu attēlu priekšskatījumus, izmantot zibspuldzes režīmu un pārslēgties starp priekšējo un aizmugurējo kameru.
Priekšnoteikumi
Lai sāktu veidot savu pirmo React Native lietotni, Expo nav vajadzīgs daudz. Vairāk par expo un expo-cli instalēšanu varat uzzināt šeit, dokumentos.
Piezīme: šajā apmācībā es izmantošu macOS un iOS. Jūs varat izmantot arī Android, nav daudz atšķirību, lietojot expo šajā brīdī.
Jūs varat instalēt expo un expo-cli globāli, izpildot šādu komandu:
npm install --global expo-cli
Expo ir nepieciešams Nodejs, lai palaistu. Jaunāko versiju varat palaist oficiālajā vietnē šeit.
Darba sākšana
Kad esat instalējis Expo un Nodejs, varat sākt jauna Expo projekta sāknēšanu ar zemāk esošo komandu:
expo init expo-camera-app
Kā instalēt paketes un palaist lietotni
Expo nodrošina mums klienta lietotni, kurā mēs varam palaist un redzēt izveidojamās lietotnes priekšskatījumu. To var lejupielādēt gan App Store, gan Google Play.
Šī ir lietotnes saskarne.

Kā uzsākt izstādes projektu
Dodieties uz lietotņu direktoriju un palaidiet lietotni.
cd expo-camera-app
Jums tiks uzdoti daži jautājumi, lai atlasītu lietotnes noklusējuma veidni. Šajā apmācībā mēs vienkārši atlasām tukšu (TypeScript) opciju, bet atkal jūs varat izvēlēties, kas jums ir piemērots.

Palaidiet lietotni
Pēc projekta sāknēšanas mēs varam palaist lietotni ar expo run

Tas pārlūkprogrammā atvērs logu, kurā varēsit redzēt žurnālus. Tas arī ģenerēs QR kodu, kuru varat skenēt, lai palaistu lietotni savā ierīcē.
Expo laba lieta ir tā, ka jums nav jāinstalē un jākonfigurē simulatori, lai palaistu lietotni. Tas joprojām dod jums iespēju palaist ekspozīciju simulatorā, taču jums pats jāinstalē un jākonfigurē simulators.
Atpakaļ uz mūsu lietotni. Pieņemot, ka esat veiksmīgi palaidis lietotni ierīcē, tas būs noklusējuma ekrāns:

Atveriet lietotņu direktoriju iecienītākajā kodu redaktorā. Es izmantoju VS kodu.
App.tsx
Izskatīsies šādi:
import {StatusBar} from 'expo-status-bar' import React from 'react' import {StyleSheet, Text, View} from 'react-native' export default function App() { return ( Open up App.tsx to start working on your app! ) } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center' } })
Kā izveidot lietotāja saskarni
Pēc projekta palaišanas ir pienācis laiks sākt izveidot kādu lietotāja saskarni.
Instalējiet ekspozīcijas kameru
Nākamais solis ir expo-camera instalēšana, piemēram:
expo install expo-camera
Mēs izveidosim vienkāršu lietotāja saskarni, kas ļaus lietotājam sākt kameras lietošanas procesu.

import {StatusBar} from 'expo-status-bar' import React from 'react' import {StyleSheet, Text, View, TouchableOpacity} from 'react-native' export default function App() { return ( Take picture ) } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center' } })
Tas ir vienkāršs lietotāja interfeiss: mēs importējam TouchableOpacity
pogu un veicam vienkāršu stilu. Ja jums ir jautājums, kā stils darbojas React Native, jūs varat apskatīt manus divus rakstus šeit:
- Veidošana React Native
- Demboxifying Flexbox in React Native
Tagad mums ir jāizmanto useState
āķis, lai pārvaldītu stāvokli un parādītu kameras skatu, kad lietotājs nospiež pogu fotografēt .
Take picture
const [startCamera,setStartCamera] = React.useState(false) const __startCamera = ()=>{ }
Lietotājam nospiežot pogu, mums ir jādara divas svarīgas lietas:
- Jautājiet atļauju piekļūt kamerai. Mobilajā izstrādē piekļuvi daudziem vietējiem API un mobilajām funkcijām bieži ierobežo lietotāja atļaujas un privātums. Tas ir tikai kaut kas tāds, pie kā jāpierod, izstrādājot mobilās lietotnes.
- Mainiet stāvokli un prezentējiet kameru.
Importēsim kameras moduli no expo-camera
šīs komandas:
import {Camera} from 'expo-camera'
Pievienojiet kameras skatu šādi:
{ camera = r }} >
Mēs varam izmantot, ref
lai piekļūtu kameras metodēm:
let camera: Camera
Nospiežot take picture
pogu, __startCamera
funkcija tiks izsaukta:
const __startCamera = async () => { const {status} = await Camera.requestPermissionsAsync() if(status === 'granted'){ // do something }else{ Alert.alert("Access denied") }
Funkcija vispirms lūgs atļauju. Ja lietotājs piešķir piekļuvi kamerai, mēs varam turpināt un atvērt kameru. Ja nē, mēs parādām vienkāršu brīdinājumu.
Pievienojiet kameras komponentu
Parādīsim kameru, kad lietotājs piešķir piekļuvi ierīces kamerai.
const __startCamera = async () => { const {status} = await Camera.requestPermissionsAsync() if (status === 'granted') { // start the camera setStartCamera(true) } else { Alert.alert('Access denied') } }
Mums ir jāveic dažas izmaiņas lietotāja saskarnē un jāpievieno nosacīta renderēšana. Kameru mēs parādām tikai tad, kad lietotājs to pieprasa, pretējā gadījumā tiek parādīts noklusējuma ekrāns.
{startCamera ? ( { camera = r }} > ) : ( Take picture )}

Forši, tagad mums jāpievieno poga, lai mēs varētu uzņemt faktisko attēlu.
Pievienojiet uzņemšanas pogu

This is a simple View
inside the camera view that has an absolute position. So we make sure that it is always on the top of the camera.
How to take a picture
The app should take a picture when capture button is pressed. That function will look like the below:
const __takePicture = async () => { if (!camera) return const photo = await camera.takePictureAsync() }
First, we check that we have access to the Camera
component using ref
:
if (!camera) return // if the camera is undefined or null, we stop the function execution
Then we take the picture by calling the takePictureAsync
method. It returns a promise and an object that contains the picture's details. The result will look like this:
Object { "height": 4224, "uri": "file:///var/mobile/Containers/Data/Application/E6740A15-93AF-4120-BF11-6E8B74AFBF93/Library/Caches/ExponentExperienceData/%2540anonymous%252Fcamera-app-ee0fa3c8-1bb1-4d62-9863-33bf26341c55/Camera/19F0C5DD-7CA6-4043-8D89-AF65A1055C7E.jpg", "width": 1952, }
We are only interested in the Picture URL uri
. After we take a picture, we have to show the photo preview and hide the camera view. To do that we will use two hooks to change the state:
const [previewVisible, setPreviewVisible] = useState(false) const [capturedImage, setCapturedImage] = useState(null)
const __takePicture = async () => { if (!camera) return const photo = await camera.takePictureAsync() console.log(photo) setPreviewVisible(true) setCapturedImage(photo) }
setPreviewVisible
to show the previewsetCapturedImage(photo)
to store the object result
Then we display the preview like this:
{previewVisible && capturedImage ? ( ) : ( { camera = r }} > )}
The CameraPreview
component looks like this:
const CameraPreview = ({photo}: any) => { console.log('sdsfds', photo) return ( ) }
And the result looks like this:

How to re-take a picture
We can add some buttons to the preview that will allow the user to perform more actions. For example, they could re-take the photo or save it.

Add the savePhoto
and retakePicture
props to the CameraPreview
component like this:
When the Re-take
button is pressed, we will have to hide the preview, remove the current picture, and show the camera again. Do that with the following code:
const __retakePicture = () => { setCapturedImage(null) setPreviewVisible(false) __startCamera() }

How to add other options – back camera, flash, and more
expo-camra offers many options for customizing the camera, like FlashMode, setting the Camera type (front/back), zooming, and so on.
How to add FlashMode
Let's add an option so the user can turn FlashMode on and off:

We simply create a small button to switch off/on the flash, like this:
⚡️
And we just change the state when the button is pressed:
const [flashMode, setFlashMode] = React.useState('off') const __handleFlashMode = () => { if (flashMode === 'on') { setFlashMode('off') } else if (flashMode === 'off') { setFlashMode('on') } else { setFlashMode('auto') } }
And then we add FlashMode props:
{ camera = r }} >
How to access the front and the back camera
We will add a button that switches between the back and front camera.
We can get the default camera type directly from the camera module like below:
const [cameraType, setCameraType] = React.useState(Camera.Constants.Type.back)
Add type
props like this:
{ camera = r }} >
And add the switch button:
{cameraType === 'front' ? '?' : '?'}
And switch function:
const __switchCamera = () => { if (cameraType === 'back') { setCameraType('front') } else { setCameraType('back') } }
Here is the result:

You can find the full source code on GitHub.
Wrapping up
In general, Expo is an amazing tool that can save you a lot of time. It helps you start building directly and saves you the pain of environment setup.
Dažreiz jūs varat izveidot vietējo paplašinājumu un rīkoties, izmantojot vietējās funkcijas savā veidā. Šajā gadījumā es iesaku izmantot reaģējošo CLI, lai jūs varētu viegli modificēt un spēlēt ar vietējo kodu.
Sveiki, mani sauc Saids Hayani. Es izveidoju abonementu iio, lai, izmantojot biļetenu, palīdzētu veidotājiem, emuāru autoriem un ietekmētājiem palielināt savu auditoriju.Pievienojieties manam adresātu sarakstam, ja vēlaties uzzināt vairāk par React Native.