http://www.hangge.com/blog/cache/detail_1615.html
React Native - 使用CameraRoll将图片保存到本地相册
React Native 的
CameraRoll API 提供了访问本地相册的功能,本文演示如何使用
CameraRoll 将图片保存到系统相册中。
1,saveToCameraRoll(tag, type?)方法介绍
(1)这个是
CameraRoll 的一个静态方法,作用是保存一张图片到相册。
(2)参数
tag 是图片的地址,为字符串类型。其内容根据不同的设备也有所不同:
- 在 Android 上:tag 是本地地址,例如:"file:///sdcard/img.png"
- 在 iOS 上:tag 可以是 url、assets-library、内存图片中的一种。
(3)参数
type 不是必须的,可选值是'
photo' 或 '
video'。用来表示存的是图片还是视频。不指定的话程序也会根据后缀自行判断。(结尾为
.mov 或
.mp4 为视频,其它为图片)
2,准备工作
(1)如果要在
iOS 上使用这个模块,我们首先要链接
RCTCameraRoll 库。进入到工程项目中的
node_module/react-native/Libraries/CameraRoll
(2)把
RCTCameraRoll.xcodeproj 添加到在项目工程的
Liberaries 文件夹下
(3)在
Build Phases ->
Link Binary With Libraries 里添加
libRCTCameraRoll.a
3,使用样例
(1)效果图
程序启动时会将一张网络图片显示在
Image 组件上。
当点击“
保存图片到相册”按钮时,会将这张图片保存到设备相簿中。同时保存成功后还会将存放的
URI 路径给弹出显示。
(2)样例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
import React, {Component} from
'react'
;
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
CameraRoll,
} from
'react-native'
;
//网络图片地址
//默认应用的容器组件
class App extends Component {
//渲染
render() {
return
(
<View style={styles.container}>
<View style={styles.image}>
<Image style={styles.img}
source={{uri: imgURL}}
resizeMode=
"contain"
/>
</View>
<View>
<Text onPress={
this
.saveImg.bind(
this
, imgURL)} style={[styles.saveImg]}>
保存图片到相册
</Text>
</View>
</View>
);
}
//保存图片
saveImg(img) {
var
promise = CameraRoll.saveToCameraRoll(img);
promise.then(
function
(result) {
alert(
'保存成功!地址如下:\n'
+ result);
}).
catch
(
function
(error) {
alert(
'保存失败!\n'
+ error);
});
}
}
//样式定义
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 30,
alignItems:
'center'
},
image:{
borderWidth:1,
width:300,
height:100,
borderRadius:5,
borderColor:
'#ccc'
},
img:{
height:98,
width:300,
},
saveImg:{
height:30,
padding:6,
textAlign:
'center'
,
backgroundColor:
'#3BC1FF'
,
color:
'#FFF'
,
marginTop:10,
}
});
AppRegistry.registerComponent(
'ReactDemo'
, () => App);
|
原文出自: www.hangge.com 转载请保留原文链接: http://www.hangge.com/blog/cache/detail_1615.html