阅读 383

react native基于react-native-image-crop-picker实现的自制图片选择

参考

效果展示

在这里插入图片描述 在这里插入图片描述

前言

  • 使用这个react-native-image-crop-picker组件是因为这个组件功能更加强大。自带了图片剪切,IOS端视频压缩。
  • 当前的实现仅能选择一张图片,通过回调的方式返回图片的信息对象。
  • 返回结果实例:
{height: 388,
mime: "image/png",
modificationDate: "1626168615000",
path: "file:///data/user/0/com.idance_app/cache/react-native-image-crop-picker/333.png",
size: 399743}
复制代码

源码

/**
 * 选择图片、视频
 * 2021-7-13
 */

import React, { useState } from 'react';
import { View, TouchableOpacity, Image } from 'react-native';
import { pxToDp } from '../../utils/stylesKits';
import Icon from 'react-native-vector-icons/FontAwesome5';
import ImagePicker from 'react-native-image-crop-picker';

interface Props {
  callBackImage: any;
  style: any;
}

const Index = (props: Props) => {
  const [image, setImage] = useState({ path: '' });
  const [isShow, setIsShow] = useState(false);

  /**
   * 选择图片
   */
  const pickImage = () => {
    ImagePicker.openPicker({
      width: pxToDp(96),
      height: pxToDp(96),
      mediaType: 'photo'
    }).then((image) => {
      setImage(image);
      setIsShow(true);
      props.callBackImage(image);
    });
  };

  const pickView = () => {
    return (
      <TouchableOpacity
        style={{
          borderStyle: 'dashed',
          borderColor: 'black',
          width: pxToDp(96),
          height: pxToDp(96),
          borderWidth: 1,
          justifyContent: 'center',
          alignItems: 'center',
          borderRadius: 0.1
        }}
        onPress={pickImage}
      >
        <Icon name="plus" size={30} color="#E8E8E8" />
      </TouchableOpacity>
    );
  };

  /**
   * 缩略图展示
   * @returns
   */
  const thumbnailView = () => {
    return (
      <View>
        <Image
          style={{ width: pxToDp(96), height: pxToDp(96), borderRadius: 10 }}
          source={{ uri: image.path }}
        />
        <TouchableOpacity
          style={{ width: pxToDp(20), position: 'absolute', top: pxToDp(-10), left: pxToDp(86) }}
          onPress={() => {
            setIsShow(!isShow);
            props.callBackImage(null);
          }}
        >
          <Image
            style={{ width: pxToDp(20), height: pxToDp(20) }}
            source={require('@/res/images/x.png')}
          />
        </TouchableOpacity>
      </View>
    );
  };

  return (
    <View style={[props.style, { width: pxToDp(110), height: pxToDp(110) }]}>
      {isShow ? thumbnailView() : pickView()}
    </View>
  );
};

Index.defaultProps = {
  callBackImage: () => {},
  style: {}
};

export default Index;

复制代码

使用实例

//回调的方法
  pickImage = (image: any) => {
    console.log(image);
  };

//组件的使用
<Pick
callBackImage={this.pickImage}
style={{ marginTop: pxToDp(20), marginLeft: pxToDp(15) }}
/>
复制代码
文章分类
前端