Image組件相似於iOS中UIImage控件,該組件能夠經過多種方式加載圖片資源。javascript
使用方式,加載方式有以下幾種:java
/** * Sample React Native App * https://github.com/facebook/react-native * 周少停 * image 加載的三種方式+設置圖片的內容模式 */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, Image, View, } from 'react-native' class Project extends Component { render() { return ( <View style={styles.container}> <Text>加載工程中圖片</Text> <Image source={require('./imgs/1111.png')} style={{width:120,height:120}}/> <Text>加載Xcode中asset的圖片,也可使用uri的方式加載</Text> <Image source={require('image!520')} style={{width:120,height:120}} /> <Text>加載網絡中的圖片</Text> <Image source={{uri:'https://unsplash.it/600/400/?random'}} style={{width:120,height:200}}/> <Text>設置加載圖片的模式</Text> <Image source={{uri:'https://unsplash.it/600/400/?random'}} style={{width:120,height:200,resizeMode:Image.resizeMode.cover}}/> <Image source={{uri:'https://unsplash.it/600/400/?random'}} style={{width:120,height:200,resizeMode:Image.resizeMode.contain}}/> <Image source={{uri:'https://unsplash.it/600/400/?random'}} style={{width:120,height:200,resizeMode:Image.resizeMode.stretch}}/> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, marginTop:20,//上邊距 flexDirection:'column',//主軸方向 垂直 justifyContent: 'flex-start',//控件在主軸上的對齊方向 alignItems: 'flex-start', //控件在側軸上的對齊方向 backgroundColor: '#F5FCFF', } }); AppRegistry.registerComponent('Project', () => Project);
/** * Sample React Native App * https://github.com/facebook/react-native * 周少停 2016-09-13 * Imaage的常見屬性 */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Image } from 'react-native'; //導入json數據 var BadgeData = require('./BadgeData.json'); //定義一些全局變量 var Dimensions = require('Dimensions'); var {width} = Dimensions.get('window'); //屏寬 var cols = 3 //總列數 var boxW = 100; //單個盒子的寬度&高度 var vMargin = (width - cols*boxW)/(cols + 1);//盒子中間的水平間距 var hMargin = 25; class Project extends Component { render() { return ( <View style={styles.container}> {/*返回包的數據*/} {this.renderAllBadge()} </View> ); } //返回全部的包 renderAllBadge(){ //定義一個數組,裝每一個包的信息 var allBadge = []; //遍歷json數據 for(var i=0;i<BadgeData.data.length;i++){ //去除單獨的數據對象 var badge = BadgeData.data[i]; //直接裝入數組 allBadge.push( <View key={i} style={styles.outViewStyle}> <Image source={{uri:badge.icon}} style={styles.imageStyle} /> <Text style={styles.mainTitleStyle}> {badge.title} </Text> </View> ); } //返回數組 return allBadge; } } const styles = StyleSheet.create({ container: { flex: 1, marginTop:20,//上邊距 flexDirection:'row',//主軸方向,水平 alignItems:'flex-start',//定義控件在側軸上的對齊方式 flexWrap:'wrap',//是否換行 backgroundColor: '#F5FCFF' }, outViewStyle: { backgroundColor:'gray', alignItems:'center', width:boxW, height:boxW, marginLeft:vMargin, marginBottom:hMargin }, imageStyle:{ width:80, height:80 }, mainTitleStyle:{ color:'white' } }); AppRegistry.registerComponent('Project', () => Project);
完整源碼下載:https://github.com/pheromone/React-Native-1 react