유미의 기록들

[React Native -8] VisionCamera 구현 본문

MDLAB 기록/차량부품거래애플리케이션

[React Native -8] VisionCamera 구현

지유미 2022. 11. 3. 01:51
728x90
반응형

이번에는 카메라를 구현해보도록하겠습니다

 

비전카메라 라이브러리 설치

npm install react-native-vision-camera": "^2.14.1

android > app > src > main > AndroidManifest.xml 에 추가

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

 

 

적용하기

import { Camera } from 'react-native-vision-camera';
class VisionCameraView extends Component {
    constructor(props) {
        super(props);

        this.camera = React.createRef();
        this.devices = [];
        this.state = {
            imageInputValue:[],
            imageURLs: [],
            device: null,
            modal: false,
          
        }
    }

    componentDidMount() {
        this.availableCameraDevices().then((select) => {
            this.setState({ device: select });
        });
    }

    async availableCameraDevices() {
        this.devices = await Camera.getAvailableCameraDevices();
        const sorted = this.devices.sort(this.devices.devices);
        return {
            back: sorted.find((d) => d.position === "back"),
            front: sorted.find((d) => d.position === "front")
        }
    }
     ...

 

 

헤더부분

 <FlatList
    data={this.state.imageURLs}
    renderItem={(item) => <ImageRender image={item} imageModal={this.handleModal} imageRemove={(index) => this.imageRemove(index)} />}
    horizontal={true} // 가로정렬
  />

imageURLs 배열 값을 하나씩 뽑아서 ImageRender클래스 image라는 파라미터로 넘겨준다

 

class ImageRender extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        const imagePath = this.props.image.item;
        const imageIndex = this.props.image.index;

        return (
            <TouchableOpacity style={styles.touchableStyle} onPress={this.props.imageModal}>
                <View style={styles.viewStyle}>
                    <ImageBackground source={{ uri: imagePath }} style={styles.image}>
                        <TouchableOpacity onPress={() => this.props.imageRemove(imageIndex)}>
                            <IconDelete name="x" size={30}></IconDelete> 
                        </TouchableOpacity>
                    </ImageBackground>
                </View>
            </TouchableOpacity >
        )
    }
}

imagePath에는 경로를, imageIndex에는 인덱스값을 props로 받는다

인덱스 값을 imageRemove메소드 파라미터로 넘겨주어 filter를 통해 걸러서 imageURLs를 초기화한다

imageRemove = (index) => {
    console.log(index);
    this.setState({
        imageURLs: this.state.imageURLs.filter((value, indexNum) => indexNum !== index)
    });
    console.log('삭제완료');
 };

 

 

카메라 부분 

 <Camera
    ref={this.camera}
    style={StyleSheet.absoluteFill}
    device={this.state.device.back}
    isActive={true}
    photo={true}
  />

 

 

 

카메라 버튼 클릭했을 때 

<TouchableOpacity style={styles.btn_camera} onPress={this.onPressButton}>
   <IconCircle name="circle-thin" size={65} color="#C0C0CE"></IconCircle>
</TouchableOpacity>
 onPressButton = async () => {
        const photo = await this.camera.current.takeSnapshot({
            flash: 'off',
        })
        this.setState({ imageURLs: this.state.imageURLs.concat('file://' + photo.path) })
    }

 

 

결과물

 

728x90
반응형
Comments