React Native 学习第六天

2018-11-20  本文已影响0人  Cheep

React Native开源库react-native-image-crop-picker使用图解

前言

React Native开发中我们会遇到修改头像、上传图片的问题,React Native是跨平台语言,需要兼容IOS和Android,自己去写会很麻烦,
所以我跟大家分享一个第三方开源库:“react-native-image-crop-picker”。

react-native-image-crop-picker

导入

...
npm i react-native-image-crop-picker --save 
react-native link react-native-image-crop-picker
...

基础使用

...
import ImagePicker from 'react-native-image-crop-picker';

export class CameraUtils extends Component{
    constructor(props){
        super(props);
        this.state = {
            imageUrl:require('xxx.png'),
            path:''
        }
    }

    render(){
        return(
            <View>
            <Image style={{width:150,height:150}} source={this.state.imageUrl}/>
            <Button
                onPress={()=>{this.onHandlePicker()}}
                title='相册'/>
            </View>
        )
    }

    //调用相册 单张图片
    onHandlePicker(){
        //从相册中选择单张图片、cropping是否切割
        ImagePicker.openPicker({
            width:300,
            height:300,
            cropping:true
        }).then(image=>{
            console.log('图片路径:'+image['path']);
            console.log('图片base64格式数据流:'+image['data']);    
            console.log('图片格式:'+image['mime']);
            console.log('图片宽度:'+image['width']);
            console.log('图片高度:'+image['height']);
            console.log('图片大小:'+image['size']);
            this.setState({
                path:image['path'],
                imageUrl:{uri:image['path']}
            })
        })
    }

    //调用相机
    onHandleCamera(){
        ImagePicker.openCamera({
            width:300,
            height:300,
            cropping:true
        }).then(image=>{
            ...
        })  
    }

    //裁剪已有的图片
    onHandleScreenShot(){
        ImagePicker.openCropper({
            path:this.state.path,   //图片路径
            width:300,
            height:300
        }).then(image =>{
            ...
        })
    }

    //调用相册 多张图片
    onHandlePickers(){
        ImagePicker.openPicker({
            multiple:true
        }).then(images=>{
            console.log('图片数量:'+images.length);
        })
    }
}
...

报错解决

如果报错提示:...com.android.support:appcompat-v7:27.1.0...
第一步:项目根目录/android/build.gradle
        ...
        allprojects{
            repositories{
                ...
                //添加
                maven{url 'https://maven.google.com'}
                
                maven{url "https://jitpack.io"}
            }
        }
第二步:项目根目录/android/app/build.gradle
        ...
        android{
            compileSdkVersion 27
            buildToolsVersion "27.0.3"
            
            defaultConfig{
                ...
                minSdkVersion 17
                targetSdkVersion 27
                vectorDrawables.useSupportLibrary = true
                ...
            }
            ...
        }
上一篇下一篇

猜你喜欢

热点阅读