1.在开始之前需要我们在Xcode去做配置,需要先链接RCTCameraRoll库。
在工程文件夹下一次进入../node_modules/react-native/Libraries/CameraRoll
找到CameraRoll文件夹下的工程
3DB12AAB-B95A-421F-B784-F4E7A6990633.png
将RCTCameraRoll工程添加到当前工程的Libraries文件夹下
5C489AC4-FF06-4A1F-B157-F2341290A522.png然后把ibRCTCameraRoll.at加在TARGETS->Build Phaese->Link Binary With Libraries里面
23FB76FC-ADA2-408F-99BE-3B56E28C7C21.png从iOS10开始,访问相册需要用户授权。你需要在Info.plist中添加一条名为NSCameraUsageDescription的键,然后在其值中填写向用户请求权限的具体描述
E77962E1-8EE4-4407-855B-E276CDAC55C3.png2.配置了上面第一步之后就可以开始写rn了,CameraRoll 给我们跑出来三个方法(参照官方文档)
1.static saveImageWithTag(tag) //保存一个图片到相册
2.static saveToCameraRoll(tag, type?) //把图片或视频保存到相册中
3.static getPhotos(params: object) //返回一个带有图片标识符对象的Promise
3.基于这些实现效果如下:
点击保存到相册之后会出现下面效果如图:
3DAD46A3-4AD2-4384-85F1-714AD89A8421.png附上源码
/**
* Created by sunbiao on 2017/7/21.
*/
import React, {Component} from 'react';
import {
StyleSheet,
View,
AsyncStorage,
Button,
Alert,
Text,
TextInput,
CameraRoll,
Image,
Dimensions,
ScrollView,
} from 'react-native';
var imgUrl = "http://diy.qqjay.com/u/files/2012/0209/2f45e7e0d06a69a974949c0872a5ec5a.jpg";
var screenWidth = Dimensions.get('window').width;
var parames={
first:4,
groupTypes:'All',
assetType:'Photos',
}
export default class MyCameraRoll1 extends Component{
// 构造
constructor(props) {
super(props);
// 初始状态
this.state = {
photos:[]
};
this.saveImgToCamera=this.saveImgToCamera.bind(this);
this.getPhotos=this.getPhotos.bind(this);
}
saveImgToCamera(){
var that = this;
var img = imgUrl;
var promise = CameraRoll.saveToCameraRoll(img);
promise.then((data)=>{
Alert.alert(data);
var photos =this.state.photos;
photos.unshift(data);
that.setState({
photos:photos,
});
},
(error)=>{Alert.alert(error)}
)
}
componentDidMount(){
this.getPhotos();
}
getPhotos(){
var that = this;
var promise = CameraRoll.getPhotos(parames);
promise.then((data)=>{
var edges = data.edges;
var photos=this.state.photos;
for (var index in edges){
photos.push(edges[index].node.image.uri);
}
that.setState({
photos:photos
})
},
(error)=>{Alert.alert(error)})
}
render(){
var photos = this.state.photos || [];
var imageView =[];
for (var index in photos){
imageView.push(
<View style={{marginHorizontal:1,borderWidth:1,borderColor:'orange'}} key={index}>
<Image source={{uri:photos[index]}}
style={{width:screenWidth/2.0-4,height:100}}/>
</View>
);
}
return(
<ScrollView>
<View style={{flex:0.4}}>
<Image
style={{width:screenWidth,height:100}}
source={{uri:imgUrl}}
/>
<Button title="保存到相册" onPress={this.saveImgToCamera} />
</View>
<View style={{flex:0.6,flexDirection:'row',flexWrap:'wrap'}}>
{imageView}
</View>
</ScrollView>
);
}
}
网友评论