使用react-native-camera實現react-native的拍照功能

安裝以及配置

官方文檔

注:請確保RN版本>0.60

針對ios

window系統開發app無需配置,因爲ios app只能使用蘋果電腦開發

安裝
1、npm install react-native-camera --save
2、cd ios && pod install && cd ..
配置

應用添加權限和使用說明ios文件夾創建Info.plist

<!-- Required with iOS 10 and higher -->
<key>NSCameraUsageDescription</key>
<string>Your message to user when the camera is accessed for the first time</string>

<!-- Required with iOS 11 and higher: include this only if you are planning to use the camera roll -->
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Your message to user when the photo library is accessed for the first time</string>

<!-- Include this only if you are planning to use the camera roll -->
<key>NSPhotoLibraryUsageDescription</key>
<string>Your message to user when the photo library is accessed for the first time</string>

<!-- Include this only if you are planning to use the microphone for video recording -->
<key>NSMicrophoneUsageDescription</key>
<string>Your message to user when the microphone is accessed for the first time</string>

注: 如果存在問題按下面文件調整Podfile文件

target 'yourTargetName' do
  # See http://facebook.github.io/react-native/docs/integration-with-existing-apps.html#configuring-cocoapods-dependencies
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'CxxBridge', # Include this for RN >= 0.47
    'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43
    'RCTText',
    'RCTNetwork',
    'RCTWebSocket', # Needed for debugging
    'RCTAnimation', # Needed for FlatList and animations running on native UI thread
    # Add any other subspecs you want to use in your project
  ]

  # Explicitly include Yoga if you are using RN >= 0.42.0
  pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  # Third party deps podspec link
  pod 'react-native-camera', path: '../node_modules/react-native-camera'

end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == "React"
      target.remove_from_project
    end
  end
end

針對Android

安裝
npm install react-native-camera --save
配置
  • android/app/src/main/java/[...]/MainApplication.java

    // 添加
    import org.reactnative.camera.RNCameraPackage;
    
    // 添加(大約27行處)
    packages.add(new RNCameraPackage());
    
  • android/settings.gradle

    // 添加到文件末尾就ok了
    include ':react-native-camera'
    project(':react-native-camera').projectDir = new File(rootProject.projectDir,     '../node_modules/react-native-camera/android')
    
  • 嚮應用android/app/src/main/AndroidManifest.xml文件添加權限:

    <!-- 讓<manifest></manifest>包裹 -->
    <!-- Required -->
    <uses-permission android:name="android.permission.CAMERA" />
    
    <!-- Include this only if you are planning to use the camera roll -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    <!-- Include this only if you are planning to use the microphone for video recording -->
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    
  • android/app/build.gradle添加以下代碼

    android {
      ...
      defaultConfig {
        ...
        missingDimensionStrategy 'react-native-camera', 'general' // <--- 添加這一行(大約在136行)
      }
    }
    
  • 添加jitpack, android/build.gradle

    // 在文件末尾添加就行了(如果存在了無需再添加)
    allprojects {
        repositories {
            maven { url "https://www.jitpack.io" }
            maven { url "https://maven.google.com" }
        }
    }
    

測試代碼

在完成上面配置後肯定迫不及待的想使用一下了,複製下面代碼粘貼到./index.js上

'use strict';
import React, { PureComponent } from 'react';
import { AppRegistry, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { RNCamera } from 'react-native-camera';
import {name as appName} from './app.json';

class ExampleApp extends PureComponent {
  render() {
    return (
      <View style={styles.container}>
        <RNCamera
          ref={ref => {
            this.camera = ref;
          }}
          style={styles.preview}
          type={RNCamera.Constants.Type.back}
          flashMode={RNCamera.Constants.FlashMode.on}
          androidCameraPermissionOptions={{
            title: 'Permission to use camera',
            message: 'We need your permission to use your camera',
            buttonPositive: 'Ok',
            buttonNegative: 'Cancel',
          }}
          androidRecordAudioPermissionOptions={{
            title: 'Permission to use audio recording',
            message: 'We need your permission to use your audio',
            buttonPositive: 'Ok',
            buttonNegative: 'Cancel',
          }}
          onGoogleVisionBarcodesDetected={({ barcodes }) => {
            console.log(barcodes);
          }}
        />
        <View style={{ flex: 0, flexDirection: 'row', justifyContent: 'center' }}>
          <TouchableOpacity onPress={this.takePicture.bind(this)} style={styles.capture}>
            <Text style={{ fontSize: 14 }}> SNAP </Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: 'black',
  },
  preview: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  capture: {
    flex: 0,
    backgroundColor: '#fff',
    borderRadius: 5,
    padding: 15,
    paddingHorizontal: 20,
    alignSelf: 'center',
    margin: 20,
  },
});

AppRegistry.registerComponent(appName, () => ExampleApp);

效果圖:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章