react-native中CameraRoll模块提供了访问本地相册的功能。

在react版本为0.23.0的项目中,不支持Android,而且在iOS中使用CameraRoll还需要我们手动操作:

iOS:

  1. 将RCTCameraRoll.xcodeproj添加到我们的项目中:展开项目 > Libraies  右键Libraies点击 “Add Files to ‘项目名’ ”,找到 项目文件夹/node_modules/react-native/Libraries/CameraRoll/RCTCameraRoll.xcodeproj , 添加到项目里。
  2. 我们要把libRCTCameraRoll.a这个苦添加到主项目的Link Binary With Libraries中,如下图:

经过这样的添加我们在项目中再使用CameraRoll里边的函数就不会出错了。

CameraRoll模块中有两个函数:saveImageWithTag()、getPhotos()。

saveImageWithTag()

保存一个图片到相册。

@param {string} tag 在安卓上,本参数是一个本地URI,例如"file:///sdcard/img.png".

在iOS设备上可能是以下之一:

  • 本地URI
  • 资源库的标签
  • 非以上两种类型,表示图片数据将会存储在内存中(并且在本进程持续的时候一直会占用内存)。

返回一个Promise,操作成功时返回新的URI。

示例:

CameraRoll.saveImageWithTag(image).then(function (success) {
Alert.alert(
'',
'保存到相册成功',
[
{text: '确定', onPress: () => console.log(success)} ]
)
}, function (error) {
Alert.alert(
'',
'保存到相册失败',
[
{text: '确定', onPress: () => console.log(error)} ]
)
}
)
}

获得相册中的照片。getPhotos()

学习这个功能是在官方demo中学习的,它写成了一个可以使用的js文件CameraRollView.js,我们需要将该文件引入我们的项目中。

CameraRollView.js文件代码:

/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @providesModule CameraRollView
* @flow
*/
'use strict'; var React = require('react');
var ReactNative = require('react-native');
var {
ActivityIndicatorIOS,
CameraRoll,
Image,
ListView,
Platform,
StyleSheet,
TouchableOpacity,
View,
} = ReactNative; var groupByEveryN = require('groupByEveryN');
var logError = require('logError'); var propTypes = {
/**
* The group where the photos will be fetched from. Possible
* values are 'Album', 'All', 'Event', 'Faces', 'Library', 'PhotoStream'
* and SavedPhotos.
*/
groupTypes: React.PropTypes.oneOf([
'Album',
'All',
'Event',
'Faces',
'Library',
'PhotoStream',
'SavedPhotos',
]), /**
* Number of images that will be fetched in one page.
*/
batchSize: React.PropTypes.number, /**
* A function that takes a single image as a parameter and renders it.
*/
renderImage: React.PropTypes.func, /**
* imagesPerRow: Number of images to be shown in each row.
*/
imagesPerRow: React.PropTypes.number, /**
* The asset type, one of 'Photos', 'Videos' or 'All'
*/
assetType: React.PropTypes.oneOf([
'Photos',
'Videos',
'All',
]), }; var CameraRollView = React.createClass({
propTypes: propTypes, getDefaultProps: function(): Object {
return {
groupTypes: 'SavedPhotos',
batchSize: 5,
imagesPerRow: 1,
assetType: 'Photos',
renderImage: function(asset) {
var imageSize = 150;
var imageStyle = [styles.image, {width: imageSize, height: imageSize}];
return (
<Image
source={asset.node.image}
style={imageStyle}
/>
);
},
};
}, getInitialState: function() {
var ds = new ListView.DataSource({rowHasChanged: this._rowHasChanged}); return {
assets: ([]: Array<Image>),
groupTypes: this.props.groupTypes,
lastCursor: (null : ?string),
assetType: this.props.assetType,
noMore: false,
loadingMore: false,
dataSource: ds,
};
}, /**
* This should be called when the image renderer is changed to tell the
* component to re-render its assets.
*/
rendererChanged: function() {
var ds = new ListView.DataSource({rowHasChanged: this._rowHasChanged});
this.state.dataSource = ds.cloneWithRows(
groupByEveryN(this.state.assets, this.props.imagesPerRow)
);
}, componentDidMount: function() {
this.fetch();
}, componentWillReceiveProps: function(nextProps: {groupTypes?: string}) {
if (this.props.groupTypes !== nextProps.groupTypes) {
this.fetch(true);
}
}, _fetch: function(clear?: boolean) {
if (clear) {
this.setState(this.getInitialState(), this.fetch);
return;
} var fetchParams: Object = {
first: this.props.batchSize,
groupTypes: this.props.groupTypes,
assetType: this.props.assetType,
};
if (Platform.OS === "android") {
// not supported in android
delete fetchParams.groupTypes;
}
if (this.state.lastCursor) {
fetchParams.after = this.state.lastCursor;
} CameraRoll.getPhotos(fetchParams)
.then((data) => this._appendAssets(data), (e) => logError(e));
}, /**
* Fetches more images from the camera roll. If clear is set to true, it will
* set the component to its initial state and re-fetch the images.
*/
fetch: function(clear?: boolean) {
if (!this.state.loadingMore) {
this.setState({loadingMore: true}, () => { this._fetch(clear); });
}
}, render: function() {
return (
<View style={{flexWrap: 'wrap'}}>
<ListView contentContainerStyle={{flex:1, flexDirection:'row',flexWrap: 'wrap', justifyContent:'center'}}
renderRow={this._renderRow}
renderFooter={this._renderFooterSpinner}
onEndReached={this._onEndReached}
style={{flex:1}}
dataSource={this.state.dataSource}
/>
</View>
);
}, _rowHasChanged: function(r1: Array<Image>, r2: Array<Image>): boolean {
if (r1.length !== r2.length) {
return true;
} for (var i = 0; i < r1.length; i++) {
if (r1[i] !== r2[i]) {
return true;
}
} return false;
}, _renderFooterSpinner: function() {
if (!this.state.noMore) {
return <ActivityIndicatorIOS style={styles.spinner} />;
}
return null;
}, // rowData is an array of images
_renderRow: function(rowData: Array<Image>, sectionID: string, rowID: string) {
var images = rowData.map((image) => {
if (image === null) {
return null;
}
return this.props.renderImage(image);
}); return (
<View>
{images}
</View>
);
}, _appendAssets: function(data: Object) {
var assets = data.edges;
var newState: Object = { loadingMore: false }; if (!data.page_info.has_next_page) {
newState.noMore = true;
} if (assets.length > 0) {
newState.lastCursor = data.page_info.end_cursor;
newState.assets = this.state.assets.concat(assets);
newState.dataSource = this.state.dataSource.cloneWithRows(
groupByEveryN(newState.assets, this.props.imagesPerRow)
);
} this.setState(newState);
}, _onEndReached: function() {
if (!this.state.noMore) {
this.fetch();
}
},
}); var styles = StyleSheet.create({
image: {
margin: 4,
},
}); module.exports = CameraRollView;

文件打开会有错误显示,只是语法不一样,这个不影响效果。

使用方法:

import CameraRollView from '../CameraRollView';

export  default class CameraRollView extends Component {
constructor(props) {
super(props);
CameraRoll.getPhotos({
first: ,
assetType: 'Photos'
}).then(function (data) { }, function (error) { })
} _renderImage(asset) {
var windowSize = require('Dimensions').get('window');
return (
<TouchableOpacity key={asset}>
<Image source={asset.node.image} style={{width: (windowSize.width-)/, height: , margin:}}/>
</TouchableOpacity>
);
} render() {
return (<View style={{flex:}}>
<CameraRollView renderImage={this._renderImage}/>
</View>
)
}
}

React Native学习-CameraRoll的更多相关文章

  1. React Native 学习-01

    React Native 学习 (学习版本 0.39) 一.环境配置 二.IDE选择 webstorm 1.webstorm配置 ①.首先是可以选择使用汉化包汉化.eu68 ②.安装插件和外部库. 由 ...

  2. react native 学习一(环境搭配和常见错误的解决)

    react native 学习一(环境搭配) 首页,按照http://reactnative.cn/docs/0.30/getting-started.html#content上的介绍,下载安装pyt ...

  3. React Native 学习资料

    React Native 学习资料 学习资料 网址 React Native中文网 https://reactnative.cn/

  4. React Native 学习(三)之 FlexBox 布局

    React Native 学习(三)之 FlexBox 布局

  5. React Native 学习笔记--进阶(二)--动画

    React Native 进阶(二)–动画 动画 流畅.有意义的动画对于移动应用用户体验来说是非常必要的.我们可以联合使用两个互补的系统:用于全局的布局动画LayoutAnimation,和用于创建更 ...

  6. iOS、swift、React Native学习常用的社区、论坛

    <!----iOS> <!----Swift>*IOS开发常用社区:http://code4app.com/ *IOS开发常用社区:http://www.cocoachina. ...

  7. react native 学习资料整理

    入门教程 深入浅出 React Native:使用 JavaScript 构建原生应用 http://www.appcoda.com/react-native-introduction/  中文版 h ...

  8. iOS 写给iOS开发者的React Native学习路线(转)

    我是一名iOS开发者,断断续续一年前开始接触React Native,最近由于工作需要,专职学习React Native也有一个多月了.网络上知识资源非常的多,但能让人豁然开朗.迅速学习的还是少数,我 ...

  9. React Native学习方法论

    这是我技术公众号的第一篇文章,也是React Native系列文章的第一篇,对我的文章感兴趣的可以加我微信16230091进行关注. 本文表面上讲React Native(以下简称RN),实际上对于学 ...

  10. react native学习资料

    一:基础学习: react-native中文文档(react native中文网,人工翻译,官网完全同步)http://react-native.cn/docs/getting-started.htm ...

随机推荐

  1. 彻底解决cookie欺骗(有问题)

    不要在公共场登陆 自己重要的用户名和密码: 不用的时候,[关闭浏览器],只点[退出],还是会有安全隐患.--没有绝对的安全由于http的无状态性,总不能每次访问页面都要输入用户名和密码,所以为了保持状 ...

  2. JS:公历、农历互转

    先申明这段代码不是我写的,纯粹只是觉的比较好用,所以记录下来以后继续使用,也同样分享给大家,大家有更好的可以推荐给我,谢谢! function CalConv(M, dateStr) { if (da ...

  3. jQuery Attributes vs. Properties

    Attributes vs. Properties attributes和properties之间的差异在特定情况下是很重要.jQuery 1.6之前 ,.attr()方法在取某些 attribute ...

  4. 如何设置box shadow的透明度

    (从已经死了一次又一次终于挂掉的百度空间人工抢救出来的,发表日期2014-04-24) 今天发现使用box-shadow属性,可以很好的给div添加阴影效果,但是添加的效果如果是: -moz-box- ...

  5. SAE J1708 DS36277 MAX3444, DS75176B

    http://en.wikipedia.org/wiki/J1708 J1708 SAE J1708 is a standard used for serial communications betw ...

  6. acdream 1738 世风日下的哗啦啦族I 分块

    世风日下的哗啦啦族I Time Limit: 20 Sec  Memory Limit: 256 MB 题目连接 http://acdream.info/problem?pid=1738 Descri ...

  7. ExtJS grid tableGrid study

    Q:  How to color the text in the grid Try: http://dev.sencha.com/playpen/docs/output/Ext.grid.TableG ...

  8. Codeforces #250 (Div. 2) C.The Child and Toy

    之前一直想着建图...遍历 可是推例子都不正确 后来看数据好像看出了点规律 就抱着试一试的心态水了一下 就....过了..... 后来想想我的思路还是对的 先抽象当前仅仅有两个点相连 想要拆分耗费最小 ...

  9. Objective-C面向对象的编程

    Objective-C面向对象的编程 目录 对面向对象编程思想的理解 类的声明和定义 类的声明和定义 对关键字super和self的理解 初始化函数 @property声明类成员 类的实例化 继承 组 ...

  10. Trie 树 及Java实现

    来源于英文“retrieval”.   Trie树就是字符树,其核心思想就是空间换时间. 举个简单的例子.   给你100000个长度不超过10的单词.对于每一个单词,我们要判断他出没出现过,如果出现 ...