# 二維碼掃碼功能
- [二維碼掃碼](https://www.twblogs.net/a/5c7c1c98bd9eee339918c505)
## 照片選擇
將使用 react-native-image-picker 套件。
### 安裝
```
$ npm install react-native-image-picker@latest --save
$ react-native link
```
### 報錯
安裝後,若看到此報錯,表示你的安裝時正確的。
後面的路徑 '/' 變爲反斜槓 '\' 將無法使用,改正過來即可。
```
include ':react-native-vector-icons'
project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
include ':react-native-image-picker'
project(':react-native-image-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-picker/android')
```
### Demo Code
``` js
import React from 'react';
import { View, Button, Image } from 'react-native';
import ImagePicker from 'react-native-image-picker';
class ImagePickerAPI extends React.Component {
state = {
avatarSource: {
uri: ''
}
}
onPressImg = () => {
const options = {
title: '選擇圖片',
cancelButtonTitle: '取消',
takePhotoButtonTitle: '拍照',
chooseFromLibraryButtonTitle: '相冊',
customButtons: [
{name: '唯一名稱', title: '顯示的自定義按鈕內容'},
],
cameraType: 'back', // 類型 'front' or 'back' ,前置還是後置攝像頭
mediaType: 'photo', // 圖片或視頻 'photo', 'video', or 'mixed' on iOS, 'photo' or 'video' on Android
videoQuality: 'high', // 視頻質量 'low', 'medium', or 'high' on iOS, 'low' or 'high' on Android
durationLimit: 10, // 最大錄製時間
maxWidth: 300, // 返回的圖片數據的最大寬 photos only 只有圖片有這個屬性
maxHeight: 300, // 返回的圖片數據的最大高 photos only
quality: 0.8, // 圖片質量 0 to 1 photos only
angle: 90,
allowsEditing: false, // 是否可以編輯
noData: false, // 如果爲true,則禁用data生成的base64 字段(極大地提高大圖片的性能)
storageOptions: {
skipBackup: true // 如果true,該照片將不會備份到iCloud
}
};
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {
console.log('取消');
}
else if (response.error) {
console.log('發生錯誤: ', response.error);
}
else if (response.customButton) {
console.log('自定義按鈕被點擊,它的名稱是:', response.customButton);
}
else {
console.log('Response = ', response); // 選擇或拍攝的照片數據對象
let source = { uri: response.uri };
// You can also display the image using data:
// let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source
});
}
});
}
_renderImg = () => {
const side = 200 ;
if(this.state.avatarSource.uri){
return(
<View>
<Image
source={{ uri: this.state.avatarSource.uri }}
style={{width:side, height:side}}
/>
</View>
);
}else{
return null;
}
}
render(){
return(
<View>
<Button
title='照片'
onPress={this.onPressImg}
/>
{this._renderImg()}
</View>
);
}
}
export default ImagePickerAPI;
```