```
import React, {Component} from 'react';
import {
Platform,
CameraRoll,
TouchableWithoutFeedback,
} from 'react-native';
import {NavigationPage} from 'teaset'
import RNFS from 'react-native-fs'
import Back from './Back'
export default class ContactUs extends NavigationPage {
state = {
pic: 'https://xxxxx.jpg' //图片的路径
}
leftBtn = () => {
return <Back onPress={() => this.navigator.pop()}></Back>
}
saveConfirm = ()=>{
Alert.alert('提示 ', '确定保存照片到相册?',
[
{text: " 取消", onPress: () => {
return
}},
{
text: "确定", onPress: () => {
if(Platform.OS === 'ios'){
this.saveImg()
}else{
this.saveImgInAndroid()
}
}
},
]
)
}
//ios保存图片
saveImg = async() => {
let prefix = 'assets-library'
var uri = await CameraRoll.saveToCameraRoll(this.state.pic, 'photo')
if (uri && uri.indexOf(prefix) === 0) {
Alert.alert('保存成功')
} else {
Alert.alert('保存失败')
}
}
//安卓保存图片
saveImgInAndroid = () => {
const storeLocation = `${RNFS.ExternalDirectoryPath}`; //安卓ExternalDirectoryPath才是挂载的外置存储,可被用户随意查看
let pathName = new Date().getTime() + "联系我们.png"
let downloadDest = `${storeLocation}/${pathName}`;
const ret = RNFS.downloadFile({fromUrl:this.state.pic,toFile:downloadDest});
ret.promise.then(res => {
if(res && res.statusCode === 200){
var promise = CameraRoll.saveToCameraRoll("file://" + downloadDest);
promise.then(function(result) {
Alert.alert("图片已保存至相册")
}).catch(function(error) {
Alert.alert("保存失败")
})
}
})
}
render() {
return <View style={{backgroundColor:'#ffffff',flex:1, }}>
<NavigationBar title={<View><Text style={{fontSize:16,color:'#ffffff'}}>联系我们</Text></View>}
left={this.leftBtn()}></NavigationBar>
<View style={{flex:1}}>
<View style={{flex: 1}}>
<View style={{display:'flex',alignItems:'center',marginTop:50}}>
<View><Text style={{color:'#333',fontSize:18}}>微信二维码</Text></View>
<TouchableWithoutFeedback onLongPress={()=>{this.saveConfirm()}}>
<Image source={{uri:this.state.pic}}
style={{width:200,height:200,marginTop:20}}></Image>
</TouchableWithoutFeedback>
</View>
}
</View>
</View>
</View>
}
}
```
参考文档https://www.jianshu.com/p/6242ec32f75f
本文介绍如何使用React Native在iOS和Android平台上保存图片到设备相册,涉及跨平台文件管理和图片处理技术。
4693

被折叠的 条评论
为什么被折叠?



