react native 为我们调用本地的图片资源提供了一个api接口CameraRoll
.
CameraRoll
CameraRoll provides access to the local camera roll / gallery. Before using this you must link the RCTCameraRoll library. You can refer to Linking for help.
CameraRoll主要的作用在于我们可以利用他来展示我们的本地的图片,来做一个图片墙,你也可以将网络上的图片保存进你的本机
CameraRoll主要为我们提供了三个方法:如下:
static saveImageWithTag(tag)
static saveToCameraRoll(tag, type?)
*Saves the photo or video to the camera roll / gallery.
On Android, the tag must be a local image or video URI, such as “file:///sdcard/img.png”.
On iOS, the tag can be any image URI (including local, remote asset-library and base64 data URIs) or a local video file URI (remote or data URIs are not supported for saving video at this time).
If the tag has a file extension of .mov or .mp4, it will be inferred as a video. Otherwise it will be treated as a photo. To override the automatic choice, you can pass an optional type parameter that must be one of ‘photo’ or ‘video’.
Returns a Promise which will resolve with the new URI.*
static getPhotos(params)
Returns a Promise with photo identifier objects from the local camera roll of the device matching shape defined by getPhotosReturnChecker.
@param {object} params See getPhotosParamChecker.
Returns a Promise which when resolved will be of shape getPhotosReturnChecker.
前两个方法是用来保存图片的,具体用法我也没有用过,这边就不多做解释
getPhotos(params)这个方法用来获取图片,可以配合image来使用。
里面用个参数params:分别可以填入
first:数字类型,想要逆序显示的照片
after:字符串类型,一个匹配前一次调用getPhotos的page_info{end_cursor}的信息指针
groupTypes:字符串类型,指定特定的组别来过滤结果。可能是Album,All和Event等值。完整的groupTypes可在源码看到
groupName:字符串类型,在改组指定一个过滤器,例如Recent Photos或一个相册名称
assetType:值为all。photos或videos的其中一个,为资源类型指定一个过渡期
mimeTypes:字符串数组类型,基于MiMe类型进行过滤
源码展示:
componentDidMount(){
CameraRoll.getPhotos({first: 5}).done(
(data) =>{
console.log(data);
this.setState({
photoSource: {uri: data.edges[3].node.image.uri}
})
},
(error) => {
console.warn(error);
}
);
}
对了还要记住加权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />