使用組件庫(kù)react-native-image-zoom-viewer,并配合使用react-native組件庫(kù)Modal組件待诅,實(shí)現(xiàn)點(diǎn)擊查看大圖,手勢(shì)放大縮小熊镣,保存圖片卑雁,等常用功能。保存圖片還得使用react-native-fs庫(kù)绪囱。這里我圖片輪播展示用的是antd里面的走馬燈测蹲。首先引入
yarn add react-native-image-zoom-viewer
yarn add react-native-fs
import {ImageViewer} from 'react-native-image-zoom-viewer'
const RNFS = require('react-native-fs'); //文件處理
首先涉及狀態(tài),Modal是否被打開(kāi)鬼吵,以及圖片下標(biāo)(index)
state = {
isImageShow: false,
index: 0,
}
點(diǎn)擊圖片扣甲,觸發(fā)點(diǎn)擊方法,更新isImageShow,并且把index賦予給狀態(tài)琉挖,再觸發(fā)打開(kāi)圖片標(biāo)題欄變化启泣。
_OpenImage = (index) => {
this.setState({
isImageShow: true,
index
},() => {
StatusBar.setTranslucent(false)
StatusBar.setBackgroundColor('#FFFFFF')
})
}
這是最主要的保存圖片的方法,并且要給予手機(jī)APP權(quán)限
savePhoto = (url) => {
this.androidDownPath = `${RNFS.DocumentDirectoryPath}/${((Math.random() * 1000) | 0)}.jpg`;
if (Platform.OS === 'ios') { //ios圖片保存
let promise = CameraRoll.saveToCameraRoll(url);
promise.then(function (result) {
alert("已保存到系統(tǒng)相冊(cè)")
}).catch(function (error) {
alert('保存失斒颈病寥茫!\n' + error);
});
} else { //Android 先下載到本地
let DownloadFileOptions = {
fromUrl: url, //下載路徑
toFile: this.androidDownPath // Local filesystem path to save the file to
}
let result = RNFS.downloadFile(DownloadFileOptions);
let _this = this;
result.promise.then(function (val) {
console.log("文件保存成功:" + _this.androidDownPath)
let promise = CameraRoll.saveToCameraRoll(_this.androidDownPath);
promise.then(function (result) {
// console.error(JSON.stringify(result))
alert("已保存到系統(tǒng)相冊(cè)")
}).catch(function (error) {
alert('保存失敗矾麻!\n' + error);
});
}, function (val) {
console.log('Error Result:' + JSON.stringify(val));
}
).catch(function (error) {
console.log(error.message);
});
}
}
給APP權(quán)限纱耻,首先在android\app\src\main\AndroidManifest.xml下先寫入權(quán)限。
<!--獲取讀寫外置存儲(chǔ)權(quán)限-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
這時(shí)候又有問(wèn)題了险耀,它會(huì)報(bào)錯(cuò),Permission denied.僅僅只是這樣弄喘,我們還是不能獲取到權(quán)限,需要讓用戶打開(kāi)APP甩牺,手動(dòng)確認(rèn)APP才能擁有權(quán)限蘑志,所以要在入口文件,寫入方法柴灯,并且在willMount里面調(diào)用
requestExternalStoragePermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: 'My App Storage Permission',
message: 'My App needs access to your storage ' +
'so you can save your photos',
},
);
return granted;
} catch (err) {
console.error('Failed to request permission ', err);
return null;
}
};
componentWillMount(){
this.requestExternalStoragePermission()
}