http://www.hangge.com/blog/cache/detail_1616.html
React Native - 使用CameraRoll获取相册图片、并显示
React Native 的 CameraRoll API 提供了访问本地相册的功能,本文演示如何使用 CameraRoll 显示相册中的图片。
1,getPhotos(params)方法介绍
(1)这个是 CameraRoll 的一个静态方法,用于获取相册中的图片。
(2)参数 params 表示获取照片的参数。
2,准备工作
如果要在 iOS 上使用这个模块,我们首先要链接 RCTCameraRoll 库。同时还需要在 Info.plist 配置请求照片相册的关描述字段。
具体操作参考我上一篇文章:React Native - 使用CameraRoll将图片保存到本地相册
3,使用样例
(1)效果图
程序启动时会显示出用户最近拍摄的6张照片(相簿中日期最新的6张图片)。
(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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
import React, {Component} from 'react';
import { AppRegistry,
StyleSheet,
Text,
View,
Image,
ScrollView,
CameraRoll,
} from 'react-native';
//照片获取参数var fetchParams = {
first: 6,
groupTypes: 'All',
assetType: 'Photos'
}//默认应用的容器组件class App extends Component { //构造函数
constructor(props) {
super(props);
this.state = {
photos: null
};
}
//页面的组件渲染完毕(render)之后执行
componentDidMount() {
var _that = this;
//获取照片
var promise = CameraRoll.getPhotos(fetchParams)
promise.then(function(data){
var edges = data.edges;
var photos = [];
for (var i in edges) {
photos.push(edges[i].node.image.uri);
}
_that.setState({
photos:photos
});
},function(err){
alert('获取照片失败!');
});
}
//渲染
render() {
var photos = this.state.photos || [];
var photosView = [];
for(var i = 0; i < 6 ; i += 2){
photosView.push(
<View key={i} style={styles.row}>
<View style={styles.flex}>
<Image resizeMode="stretch" style={styles.image} source={{uri:photos[i]}}/>
</View>
<View style={styles.flex}>
<Image resizeMode="stretch" style={styles.image} source={{uri:photos[i+1]}}/>
</View>
</View>
)
}
return (
<ScrollView>
<View style={styles.container}>
{photosView}
</View>
</ScrollView>
);
}
}//样式定义const styles = StyleSheet.create({ flex:{
flex:1
},
container: {
flex: 1,
paddingTop: 30,
alignItems:'center'
},
row:{
flexDirection: 'row'
},
image:{
height: 120,
marginTop: 10,
marginLeft: 5,
marginRight: 5,
borderWidth: 1,
borderColor: '#ddd'
},
});AppRegistry.registerComponent('ReactDemo', () => App);
|
原文出自:www.hangge.com 转载请保留原文链接:http://www.hangge.com/blog/cache/detail_1616.html