native react 图片裁剪_react native 头像上传 react-native-image-crop-picker

之前用的是react-native-image-picker,但是当往服务器端传的时候才发现,因为没有图片裁切,所以图片过大,无法保存,所以只好更换成react-native-image-crop-picker。

react-native-image-crop-picker 不像 react-native-image-picker 直接就有弹出框,然后根据选择跳入到相应的相机或相册中,所以需要我们自定义弹出框,这里使用的是 modal。

react-native-image-crop-picker 的导入及配置这里就不说了,可以参考github上:

https://github.com/ivpusic/react-native-image-crop-picker

1、自定义弹出框(modal)

react native 提供的 Alert 局限性较大,没有办法自定义,所以我这里选择用 Modal 来实现。

简单了解:Modal组件可以用来覆盖包含 react native 根视图的原生视图,在嵌入 react native 的混合应用中可以使用 modal,modal 可以使你应用中 RN 编写的那部分内容覆盖在原生视图上显示。

常见属性:

visible // 是否可见 false/true

animationType // 动画 none:无/slide:从底部/fade:淡入淡出

transparent = {true} // 是否默认半透明

onRequestClose={()=> this.onRequestClose()} // 弹出框关闭回调

visible={this.state.modalVisible}

animationType={'fade'}

transparent = {true}

onRequestClose={()=> this.onRequestClose()}

>

请选择

打开相机

打开相册

取消

用 state 中 modalVisible 的状态来管理弹出框的显示与关闭。

style样式:

alertBackground:{

flex:1,

alignItems:'center',

justifyContent:'center',

backgroundColor:'rgba(0, 0, 0, 0.5)’, // 如果要遮罩要显示成半透明状态,这里一定要设置,reba中的a控制透明度,取值在 0.0 ~ 1.0 范围内。

},

alertBox: {

width:200,

height:175,

backgroundColor:'white',

},

_openCamera: // 调用相机,这里就要用到 react-native-image-crop-picker 了,所以记得 import 它。

// 是一个异步加载,当正确是返回 image ,这里面就是我们需要的图片信息。

ImagePicker.openCamera({

width:300,

height:400,

cropping:true

}).then(image => {

let source = {uri: image.path};

this._fetchImage(image);

this.setState({

avatarSource: source // 将图片存于本地

});

});

_openPicker: // 调用相册

ImagePicker.openPicker({

width:300,

height:400,

cropping: true

}).then(image => {

let source = {uri: image.path};

this._fetchImage(image);

this.setState({

avatarSource: source

});

});

将图片文件上传:

_fetchImage(image) {

let url = “http:。。。。。。。。”; // 接口地址

let file = {uri: image.path, type: 'multipart/form-data', name:’image.png' } ; // file 中这三个元素缺一不可。 type 必须为 multipart/form-data。

let formData = new FormData();

formData.append('file', file); // 这里的 file 要与后台名字对应。

fetch(url,{

method:'POST',

headers:{

'Content-Type':'multipart/form-data',

},

body:formData,

}).then(function (response) {

console.log("response",response);

return response.json();

})

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值