不管在Android还是在ios原生的开发中,图片都是作为控件给出来的,在RN中也有这么一个控件(Image)。根据官网的资料,图片分为本地静态图片,网络图片和混合app资源。一下分类介绍来源官网。
静态图片资源
- <Image source={require('./my-icon.png')} />
图片文件的查找会和JS模块的查找方式一样。在上面的这个例子里,是哪个组件引用了这个图片,Packager就会去这个组件所在的文件夹下查找my-icon.png。并且,如果你有my-icon.ios.png和my-icon.android.png,Packager就会根据平台而选择不同的文件。二对于ios还可能有2倍图和3倍图的区分。
- ├── button.js
- └── img
- ├── check@2x.png
- └── check@3x.png
Packager会打包所有的图片并且依据屏幕精度提供对应的资源。譬如说,iPhone 5s会使用check@2x.png,而Nexus 5上则会使用check@3x.png。如果没有图片恰好满足屏幕分辨率,则会自动选中最接近的一个图片。
- // 正确
- <Image source={'./my-icon.png')} />
-
- // 错误
- var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
- <Image source={require('./' + icon + '.png')} />
-
- // 正确
- var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png');
- <Image source={icon} />
混合App的图片资源
加载本地图库图片
static saveImageWithTag(tag) 保存一个图片到相册。
@param {string} tag 在安卓上,本参数是一个本地URI,例如"file:///sdcard/img.png".在iOS设备上可能是以下之一:
本地URI
资源库的标签
非以上两种类型,表示图片数据将会存储在内存中(并且在本进程持续的时候一直会占用内存)。
返回一个Promise,操作成功时返回新的URI。
static getPhotos(params: object) 获取图片
返回一个带有图片标识符对象的Promise。返回的对象的结构参见getPhotosReturnChecker。@param {object} 要求的参数结构参见getPhotosParamChecker.
返回一个Promise,操作成功时返回符合getPhotosReturnChecker结构的对象。
不过网上提供了第三方的组件react-native-image-picker,这个组件同时支持photo和video,也就是照片和视频都可以用。我们使用npm安装这个组件:
npm install --save react-native-image-picker
典型使用方法
- import ImagePickerManager from 'NativeModules';
- 当你想展示相机还是相册这个选择器时:(变量options还有其它的设置,一些使用它的默认值就可以满足我们的要求,以下是我使用到的)
- var options = {
- title: 'Select Avatar',// 选择器的标题,可以设置为空来不显示标题
- cancelButtonTitle: 'Cancel',takePhotoButtonTitle: 'Take Photo...',// 调取摄像头的按钮,可以设置为空使用户不可选择拍照
- chooseFromLibraryButtonTitle: 'Choose from Library...',// 调取相册的按钮,可以设置为空使用户不可选择相册照片
- customButtons: {
- 'Choose Photo from Facebook': 'fb',// [按钮文字] : [当选择这个按钮时返回的字符串]
- },mediaType: 'photo',// 'photo' or 'video'
- videoQuality: 'high',// 'low','medium',or 'high'
- durationLimit: 10,// video recording max time in seconds
- maxWidth: 100,// photos only默认为手机屏幕的宽,高与宽一样,为正方形照片
- maxHeight: 100,// photos only
- allowsEditing: false,// 当用户选择过照片之后是否允许再次编辑图片
- };
- ImagePickerManager.showImagePicker(options,(response) => {
- console.log('Response = ',response);
- if (response.didCancel) {
- console.log('User cancelled image picker');
- }
- else if (response.error) {
- console.log('ImagePickerManager Error: ',response.error);
- }
- else if (response.customButton) {
- // 这是当用户选择customButtons自定义的按钮时,才执行
- console.log('User tapped custom button: ',response.customButton);
- }
- else {
- // You can display the image using either data:
- if (Platform.OS === 'android') {
- source = {uri: response.uri,isStatic: true};
- } else {
- source = {
- uri: response.uri.replace('file://',''),isStatic: true
- };
- }
- this.setState({
- avatarSource: source
- });
- }
- });
如果我们只想直接打开相册或者相机。
- // Launch Camera:
- ImagePickerManager.ImagePickerManager.launchCamera(options,(response) => {
- // Same code as in above section!
- });
- // Open Image Library:
- ImagePickerManager.ImagePickerManager.launchImageLibrary(options,(response) => {
- // Same code as in above section!
- });
复杂功能介绍
- import React,{ Component } from 'react';
- import {
- AppRegistry,StyleSheet,Text,View,Image
- } from 'react-native';
- // 导入JSON数据
- var productData = require('./productData.json');
- var Dimensions = require('Dimensions');
- var screenW = Dimensions.get('window').width;
- // 定义一些全局的变量
- var cols = 3;
- var BoxW = 100;
- var vMargin = (screenW - cols * BoxW) / (cols + 1);
- var hMargin = 20;
- class ImageDemo extends Component {
- render() {
- return (
- <View style={styles.container}>
- {/*返回商品列表*/}
- {this.renderAllProduct()}
- </View>
- );
- }
- // 返回商品列表
- renderAllProduct() {
- // 定义数组装所有子组件
- var allProduct = [];
- console.log(productData.data.length);
- // 遍历json数据
- for(var i=0;i<productData.data.length;i++){
- // 取出单个商品数据对象
- var product = productData.data[i];
- // 装入数组
- allProduct.push(
- <View key={i} style={styles.outViewStyle}>
- <Image source={{uri:product.icon}} style={styles.iconStyle}/>
- <Text style={styles.nameStyle}>{product.name}</Text>
- </View>
- );
- }
- // 最后要返回数组
- return allProduct;
- }
- }
- const styles = StyleSheet.create({
- container: {
- flex: 1,backgroundColor: '#F5FCFF',marginTop:20,// 设置主轴的方向
- flexDirection:'row',// 换行显示
- flexWrap:'wrap'
- },outViewStyle:{
- backgroundColor:'grey',// 设置侧轴对齐方式
- alignItems:'center',width:BoxW,height:BoxW,marginLeft:vMargin,marginBottom:hMargin
- },iconStyle:{
- width:80,height:80
- },nameStyle:{
- alignItems:'center',// 文字颜色
- color:"#fff"
- }
- });
- AppRegistry.registerComponent('ImageDemo',() => ImageDemo);
json数据