美文网首页
ReactNative图片

ReactNative图片

作者: 玄策 | 来源:发表于2017-12-11 15:18 被阅读64次

目录

  • 1)基本图片
  • 2)图片缓存
  • 3)加载完毕前显示默认图片

1)基本图片

加载方式 说明
source={{uri:'icon1'}} 加载原生内图片,必须设置长宽
source={{uri:'http://xxx.png'}} 加载网络图片,必须设置长宽
source={require('../res/xx.png')} 加载路径下图片,不用设置长宽
resizeMode 说明
resizeMode='cover' 等比例缩放并填充满
resizeMode='contain' 等比例缩放并不会充满
resizeMode='stretch' 非等比例拉伸并填充
resizeMode='center' 居中不拉伸
backgroundColor:'transparent' //Image内嵌Text,文字会有背景色。在Image中使用此属性即可
source={this.props.active ? require('./a.png') : require('./b.png'} //由于不允许拼接,三元运算须用此格式

iOS9特性要求App内访问的网络必须使用HTTPS协议
需要在xcode中,在Info.plist中添加NSAppTransportSecurity类型Dictionary,
在NSAppTransportSecurity下添加NSAllowsArbitraryLoads类型Boolean,值设为YES
方可访问http地址的图片


2)图片缓存

source={{cache: '缓存策略'}} 说明
default 使用原生平台默认策略
reload URL的数据将从原始地址加载。不使用现有的缓存数据
force-cache 现有的缓存数据将用于满足请求,忽略其期限或到期日。如果缓存中没有对应请求的数据,则从原始地址加载
only-if-cached 现有的缓存数据将用于满足请求,忽略其期限或到期日。如果缓存中没有对应请求的数据,则不尝试从原始地址加载,并且认为请求是失败的
default || force-cache

3)加载完毕前显示默认图片

加载完毕前显示默认图片
export default class ImageHome extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loadNum:0,
        };
    }

    //加载开始时调用
    _onLoadStart = ()=>{
        console.log('onLoadStart')
    }
    //加载成功完成时调用此回调函数
    _onLoad = ()=>{
        console.log('onLoad');
    }
    //加载结束后,不论成功还是失败,调用此回调函数
    _onLoadEnd = ()=>{
        console.log('onLoadEnd');
    }
    //[ios]当加载错误的时候调用此回调函数,参数为{nativeEvent: {error}}
    onError(e){
        console.log('onError='+e.nativeEvent.error);
    }
    //[ios]在加载过程中不断调用,参数为{nativeEvent: {loaded, total}}
    onProgress(e){
        console.log('onProgress= 当前='+e.nativeEvent.loaded+' +总数='+e.nativeEvent.total);
        console.log('进度='+Math.round(100 * e.nativeEvent.loaded / e.nativeEvent.total));
        this.setState({
            loadNum:Math.round(100 * e.nativeEvent.loaded / e.nativeEvent.total),
        });
    }
    render() {
        return (
            <View style={styles.container}>
            <Image
                onLoadStart={this.onLoadStart}
                onLoad={this._onLoad}
                onLoadEnd={this.onLoadEnd}
                onError={e=>this.onError(e)}
                onProgress={e=>this.onProgress(e)}
                style={{width:200,height:200}}
                source={{
                    uri: 'http://images.gaga.me/photos/ymd/5425ba1d6083631839c7c45684144eae.jpg',
                    cache: 'force-cache'
                }}>
                {this.state.loadNum == 100 
                    ?
                    null
                    :
                    <View style={{backgroundColor:'#d5d5d5',width:200,height:200,alignItems:'center',justifyContent:'center'}}>
                        <ActivityIndicator/>
                    </View>
                }
            </Image>   
            </View>
        );
    }
}

参考资料

官网


相关文章

网友评论

      本文标题:ReactNative图片

      本文链接:https://www.haomeiwen.com/subject/akpiixtx.html