Programmer's Note

コード読み書きの備忘録。

React Nativeでカメラを使ってみる

React NativeでiPhoneでカメラを使うことができた。以下メモ。

プロジェクトのルートディレクトリを<ProjectRoot>とする。

パッケージのインストール

$ cd <ProjectRoot>
$ npm install react-native-camera --save
$ npx react-native link react-native-camera
$ cd pod
$ pod install

iOSのinfo.plistの編集

<ProjectRoot>ios/の下の、*.xcworkspaceをダブルクリックして、XCodeを起動する。 下記画面のInfoを編集する。

f:id:hifistar:20200825070302p:plain
XCodeのCustom iOS Target Properties

Application requires iPhone environment+をクリックして、リストから Privacy - Camera Usage Descrptionを選んで項目を追加する。 Valueに適当な文字列を入れる。

サンプルコード

いろいろ参考にして作ったサンプルコード。 SNAPボタンで撮って結果を小さいサムネに貼る。 なんかモバイル界隈は変化が速いので、1年後には動かないコードになってそうだけど。 react-nativeのバージョンは4.12.0。

import React, {Component} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  View,
  Button,
  Image,
} from 'react-native';

import {RNCamera} from 'react-native-camera'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      0: 'https://reactnative.dev/docs/assets/p_cat1.png',
    }
  }

  takePicture = async () => {
    if (this.camera) {
      const options = {quality: 0.5, base64: true}
      const data = await this.camera.takePictureAsync(options)
      console.log(data.uri)
      this.setState({0: data.uri})
    }
  }

  render() {
    return (
      <SafeAreaView style={{flex:1}}>
        <View style={styles.container}>
          <RNCamera
            ref={ref => this.camera = ref}
            type={RNCamera.Constants.Type.back}
            captureAudio={false}
            flashMode={RNCamera.Constants.FlashMode.on}
            style={[{ flex: 8 }, styles.preview]}
          />
          <View style={{ flex: 1, flexDirection: 'row'}}>
            <Image source={{ uri: this.state[0] }} style={styles.thumb} />
            <View style={{flex:2}}>
              <Button
                title='SNAP'
                onPress={this.takePicture.bind(this)}
              />
            </View>
            <View style={{flex: 1}}/>
          </View>
        </View>
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    justifyContent: 'center',
  },
  preview: {
    justifyContent: 'flex-end',
    alignItems: 'center'
  },
  thumb: {
    flex: 1,
    backgroundColor: 'yellow',
    borderWidth: 1
  }

});

export default App;