安裝 并 link
yarn add react-native-image-picker
react-native link
配置權(quán)限
Ios
android
在/android/app/src/main/AndroidManifest.xml文件中添加
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
直接上代碼
1.引入包
import ImagePicker from 'react-native-image-picker';
2.配置文案和參數(shù)卫漫,調(diào)用。
selectPhotoTapped(){
const options = {
title:'選擇圖片',
cancelButtonTitle:'取消',
takePhotoButtonTitle:'拍照',
chooseFromLibraryButtonTitle:'相冊',
mediaType:'photo',
allowsEditing:true,
}
ImagePicker.showImagePicker(options,(response)=>{
if(response.didCancel){
console.warn('cancel')
}else if(response.error){
console.warn(error)
}else{
let source = {uri:response.uri}
this.setState({
headSource:source,
})
}
});
}
以上調(diào)用彈出的選擇框是默認(rèn)的,安卓和ios的差距很大损俭,而且安卓上的彈框可丑可丑渗磅。旗扑。
一般都自定義彈框殊校,點(diǎn)擊相機(jī)
const options = {
title:'選擇圖片',
cancelButtonTitle:'取消',
takePhotoButtonTitle:'拍照',
chooseFromLibraryButtonTitle:'相冊',
mediaType:'photo',
allowsEditing:true,
}
ImagePicker.launchCamera(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
const source = { uri: response.uri };
this.setState({
headSource: source,
headImgDataStr: response.data
},()=>{
this._unloadHeadImage();
});
}
});
點(diǎn)擊相冊
const options = {
title:'選擇圖片',
cancelButtonTitle:'取消',
takePhotoButtonTitle:'拍照',
chooseFromLibraryButtonTitle:'相冊',
mediaType:'photo',
allowsEditing:true,
}
ImagePicker.launchImageLibrary(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
const source = { uri: response.uri };
console.log(response.data);
this.setState({
headSource: source,
headImgDataStr: response.data
},()=>{
this._unloadHeadImage();
});
}
});
我這里有一個(gè)問題芦疏,Ios平臺上ImagePicker.launchImageLibrary第二次調(diào)用打不開相冊肢预。如果你知道原因矛洞,求告知!L逃场沼本!