这几天在做React Native 图片相关,记录一下
操作步骤:
1.在项目中导入react-native-image-picker包
npm install react-native-image-picker@latest --save
2.需要修改项目中Android目录下的类容
<1>修改Android目录下的setting.gradle,添加
include ':react-native-image-picker'
project(':react-native-image-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-picker/android')
<2>在Android/app下的build.gradle的dependencies中添加
compile project(':react-native-image-picker')
<3>修改app/src/java/com/demo/MainApplication.java中的getPackages()中添加
new ImagePickerPackage()
如下
@Override
protected List getPackages() {
return Arrays.asList(
new MainReactPackage(),
new ImagePickerPackage()
);
}
3.在React Native 中的js文件中导入ImagePicker
import ImagePicker from 'react-native-image-picker';
4.使用:
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
PixelRatio,
TouchableOpacity,
Image,
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
export default class App extends React.Component {
state = {
avatarSource: null,
videoSource: null
};
selectPhotoTapped() {
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
storageOptions: {
skipBackup: true
}
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
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
});
}
});
}
selectVideoTapped() {
const options = {
title: 'Video Picker',
takePhotoButtonTitle: 'Take Video...',
mediaType: 'video',
videoQuality: 'medium'
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled video picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
this.setState({
videoSource: response.uri
});
}
});
}
render() {
return (
{ this.state.avatarSource === null ? Select a Photo :
}
Select a Video
{ this.state.videoSource &&
{this.state.videoSource}
}
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
},
avatarContainer: {
borderColor: '#9B9B9B',
borderWidth: 1 / PixelRatio.get(),
justifyContent: 'center',
alignItems: 'center'
},
avatar: {
borderRadius: 75,
width: 150,
height: 150
}
});
以上代码引用自
链接ImagePicker官网
https://github.com/react-comm...