当前位置: 首页>后端>正文

react-native Image picker

import React, {Component} from 'react';
import {
    ScrollView, View, Text, TouchableOpacity, TextInput, Image
} from "react-native";
import Util from "../../../app2/common/util";
import Header from "../../common/header";
import ActionSheet from "react-native-actionsheet";
import Loading from "../../../app2/common/loading";
import Toast from "../../../app2/common/ToastUtil";
import ImagePicker from "react-native-image-crop-picker";

class Y_Suggest extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            loaded: false,
            contentText:'',
            photos:[],
        };
    }


    //权限
    requestPermission = async () => {
        try {
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                {
                    title: '申请读写手机存储权限',
                    message:
                        '一个很牛逼的应用想借用你的摄像头,' +
                        '然后你就可以拍出酷炫的皂片啦。',
                    buttonNeutral: '等会再问我',
                    buttonNegative: '不行',
                    buttonPositive: '好吧',
                },
            );
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                console.log('现在你获得摄像头权限了');
            } else {
                console.log('用户并不给你');
            }
        } catch (err) {
            console.warn(err);
        }
    };

    //吊起选择框
    async _imagePicker(){
        this.requestPermission();

        let newPhotos = this.state.photos

        if(newPhotos.length>=6){
            Toast.show("图片最多为6张")
            return
        }

        this.ActionSheet.show()
    }

    //相册选择
    selectFromAlbum(){
        console.warn('您选择的是相册')

        ImagePicker.openPicker({
            multiple: true
        }).then(photos => {
            console.warn('选中的图片===',photos);
            this.setState({
                isLoading:true
            })


            let arr = this.state.photos
            photos.map((item,id)=>{
                console.warn('选中的图片item===',item);
                arr.push(item)
                this.uploadImage(item.path)

            })

            this.setState({
                photos:arr
            })

            // let imageArr = []
            // const arr = photos.map(v => {
            //     let strArr = v.path.split('/')
            //     // console.warn('strArr========',strArr[strArr.length-1])
            //     let imgName = strArr[strArr.length-1]
            //     imageArr.push(imgName)
            //     // console.warn('str====',str,imgName)
            //     let newObj = Object.defineProperty(v, 'imageName', {
            //         value : imgName,
            //         writable : true,
            //         enumerable : true,
            //         configurable : true
            //     });
            //     return newObj
            // });
            //
            // // console.warn('选择成功',arr);
            // let newArr = []
            // if(this.state.photos.length>0){
            //     newArr.concat(this.state.photos,arr)
            //     this.setState({
            //         photos: newArr,
            //         // imgNameArr:imageArr
            //     });
            // }else{
            //     this.setState({
            //         photos: arr,
            //         // imgNameArr:imageArr
            //     });
            // }


        }).catch(()=>{
            console.warn("取消选择")
        });


    }

    //相机拍摄
    selectphotograph(){
        console.warn('选择的是相机拍摄')
        let newPhotos = this.state.photos

        if(newPhotos.length===3){
            alert("图片最多为3张")
            return
        }

        // this.requestPermission();  //吊起相机时访问权限

        ImagePicker.openCamera({
            width: 300,
            height: 400,
            cropping: true,
        }).then(photos => {
            console.log(photos);
            let arr = newPhotos.concat(photos)

            this.setState({
                photos: arr,
                // imgNameArr:imageArr
            });

            let newArr = this.state.photos

            console.warn('newPhotosArr==',newArr,'newPhotosArr.length===',newArr.length)

            this.uploadImage(photos.path,newArr.length)



            // console.log('拍摄一张===',photos,'多长图片数组====',one);
            // one.map((item,id)=>{
            //     // console.warn('选中的图片item===',item);
            //     this.uploadImage(item.path)
            // })

            // let imageArr = []
            // const arr = one.map(v => {
            //     let strArr = v.path.split('/')
            //     // console.warn('strArr========',strArr[strArr.length-1])
            //     let imgName = strArr[strArr.length-1]
            //     imageArr.push(imgName)
            //     // console.warn('str====',str,imgName)
            //     let newObj = Object.defineProperty(v, 'imageName', {
            //         value : imgName,
            //         writable : true,
            //         enumerable : true,
            //         configurable : true
            //     });
            //     return newObj
            // });


        });

    }


    submit(){
        console.warn('提交')
    }

    render() {
        let photos = this.state.photos
        return (
            <View style={{flex: 1}}>
                {this.state.loaded ?
                    <View style={{flex: 1}}>
                        {Util.loading()}
                    </View>
                    :
                    <View style={{flex: 1, backgroundColor: "#fff"}}>
                        <Header headerType={3} navigation={this.props.navigation} initObj={{hideBack:false,title:'改善建议',borderBottomColor:true}}/>

                        <ScrollView>
                            <View style={{flex:1,backgroundColor:'#fff',paddingHorizontal:15}}>
                                <View style={{height:54,justifyContent:'center',paddingHorizontal:5,}}>
                                    <Text style={{color:'#0B0B34',fontWeight:'bold',fontSize:16}}>改善建议</Text>
                                </View>
                                <View style={{padding:5,paddingHorizontal:5,backgroundColor:'#FBFBFD',borderRadius:5}}>
                                    <TextInput
                                        textAlignVertical='top'
                                        style={{fontSize:13,height:125}}
                                        placeholder={'请您填写您的宝贵建议以便我们提供更好的服务'}
                                        placeholderTextColor="#B6B6C5"
                                        multiline={true}  //允许多行输入
                                        maxLength={300}
                                        underlineColorAndroid={'transparent'}
                                        clearButtonMode={'always'}
                                        onChangeText={(text)=>this.setState({contentText:text})}
                                    />
                                    <Text style={{textAlign:'right'}}>{this.state.contentText.length}/300</Text>
                                </View>

                                <View style={{marginTop:25,marginBottom:15}}>
                                    <Text style={{color:'#0B0B34',fontSize:16,fontWeight:'bold'}}>图片<Text style={{color:'#B6B6C5',fontSize:13,fontWeight:'normal'}}>(选填)</Text></Text>
                                </View>

                                {/*图片选择*/}
                                <ActionSheet
                                    ref={o => this.ActionSheet = o}
                                    title={'请选择照片类型'}
                                    options={['选择相册', '相机', '取消']}
                                    cancelButtonIndex={2}
                                    destructiveButtonIndex={1}
                                    onPress={(index) => { if(index===0){this.selectFromAlbum()}else if(index===1){this.selectphotograph()}}}
                                />

                                <Loading isLoading={this.state.isLoading} loadingText={'图片上传中'}/>

                                <View style={{flexDirection:'row',flexWrap:'wrap'}}>
                                {
                                    photos.map((item, index) => {
                                        let source = {uri: item.path};
                                        if (item.enableBase64) {
                                            source = {uri: item.base64};
                                        }
                                        return (
                                            // <View style={{width: Util.size.width/3.5,height:Util.size.width/3.5,backgroundColor:'skyblue'}}>
                                            <Image
                                                key={`image-${index}`}
                                                style={{
                                                    borderRadius:5,
                                                    width:Util.size.width/3.5,
                                                    height:Util.size.width/3.5,
                                                    marginTop:(Util.size.width-(Util.size.width/3.5)*3)/3-14,
                                                    marginLeft:(Util.size.width-(Util.size.width/3.5)*3)/3-14
                                                }}
                                                source={source}
                                                resizeMode={'cover'}
                                            />
                                            // </View>
                                        );
                                    })
                                }
                                <TouchableOpacity
                                    style={{
                                        width: Util.size.width/3.5,
                                        height:Util.size.width/3.5,
                                        // backgroundColor:'red',
                                        marginTop:(Util.size.width-(Util.size.width/3.5)*3)/3-14,
                                        marginLeft:(Util.size.width-(Util.size.width/3.5)*3)/3-14,
                                    }}
                                    onPress={()=>this._imagePicker()}
                                >
                                    <Image source={require('../../../src/L_IM_imgs/add_img.png')}
                                           style={{
                                               width: Util.size.width/3.5,
                                               height:Util.size.width/3.5,resizeMode :'center'}}/>
                                </TouchableOpacity>

                            </View>

                                <View style={{marginTop:25,marginBottom:15}}>
                                    <Text style={{color:'#0B0B34',fontSize:16,fontWeight:'bold'}}>图片<Text style={{color:'#B6B6C5',fontSize:13,fontWeight:'normal'}}>(选填)</Text></Text>
                                </View>
                                <View style={{height:54,justifyContent:'center',borderRadius:5,backgroundColor:'#FBFBFD',paddingHorizontal:5}}>
                                    <TextInput
                                        placeholder="选填,便于我们与您联系"
                                        placeholderTextColor='#B6B6C5'
                                        multiline={false}
                                        maxLength={11}
                                        style={{fontSize:16}}
                                        onChangeText={(text)=>this.setState({title:text})}
                                        underlineColorAndroid={'transparent'}
                                    />
                                </View>

                                <TouchableOpacity
                                    onPress={()=>this.submit()}
                                    style={{marginTop:40,height:54,justifyContent:'center',borderRadius:5,backgroundColor:'#1E1BF0',paddingHorizontal:5,alignItems:'center'}}>
                                    <Text style={{color:'#fff',fontSize:15}}>提交</Text>
                                </TouchableOpacity>

                            </View>

                        </ScrollView>
                    </View>
                }

            </View>
        )
    }
}

export default Y_Suggest;


https://www.xamrdz.com/backend/3dg1994731.html

相关文章: