React Native--Image控件

我的博客原文地址

基本用法

加載本地圖片

<Image source={require('./img/baidu.png')}/>

加載App內資源圖片

<Image source={{uri: 'ic_launcher'}} style={{width: 140, height: 140}} />

加載網絡圖片

<Image source={{uri:'http://172.17.137.68/heqiang/2.jpg'}} style={{width: 200, height: 200}}/>

資源圖片和網絡圖片必須聲明圖片寬高,否則不顯示。

適配不同平臺

有時我們希望在不同平臺之間用不同的圖片
比如baidu.android.png,baidu.ios.png,代碼中只需要寫baidu.png,便可以適配android和ios平臺
[email protected][email protected]還可以適配不同分辨率的機型。如果沒有圖片恰好滿足屏幕分辨率,則會自動選中最接近的一個圖片。這點是和Android中是類似的。

代碼

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image
} from 'react-native';

class HelloWorldAppp extends Component{
  render() {
    console.log("render()");
    return (
      <View>
        <Text style={styles.title_text}>本地圖片</Text>
        <Image source={require('./img/baidu.png')}/>
        <Text style={styles.title_text}>資源圖片</Text>
        <Image source={{uri: 'ic_launcher'}} style={{width: 140, height: 140}} />
        <Text style={styles.title_text}>網絡圖片</Text>
        <Image source={{uri:'http://*******.jpg'}} style={{width: 200, height: 200}}/>
    );
  }
}

AppRegistry.registerComponent('AwesomeProject', () => HelloWorldAppp);

const styles = StyleSheet.create({
  title_text:{
    fontSize:18,
  }

});

效果圖

效果圖

回調函數和屬性

  • onLayout:layout時調用,與View組件的onLayout函數類似
  • onLoadStart:開始加載時調用
  • onLoadEnd加載結束時調用
  • onLoad:成功讀取圖片時調用
        <Image source={{uri:'http://172.17.137.68/heqiang/23.jpg'}} style={{width: 200, height: 200}} 
          onLoad={function(){console.log("onLoad");}}
          onLayout={function(){console.log("onLayout");}}
          onLoadStart={function(){console.log("onLoadStart");}}
          onLoadEnd={function(){console.log("onLoadEnd");}}
          />
  • resizeMode

    • cover:在顯示比例不失真的情況下填充整個顯示區域。可以對圖片進行放大或者縮小,超出顯示區域的部分不顯示,也就是說,圖片可能部分會顯示不了。
    • contain:要求顯示整張圖片,可以對它進行等比縮小,圖片會顯示完整,可能會露出Image控件的底色。如果圖片寬高都小於控件寬高,則不會對圖片進行放大。
    • stretch:不考慮保持圖片原來的寬高比,填充整個Image定義的顯示區域,這種模式顯示的圖片可能會畸形和失真。
    • center:居中不縮放

    resizeMode也可以定義在style中,但在屬性上定義的優先級比style中高。比如下面設置中最終生效的是Image.resizeMode.center。

        <Image source={{uri:'http://172.17.137.68/heqiang/test.png'}} 
          style={{width: 200, height: 200, backgroundColor: 'grey',resizeMode: Image.resizeMode.contain}} 
          resizeMode={Image.resizeMode.center}
          />

樣式風格

  • FlexBox 支持彈性盒子風格
  • Transforms 支持屬性動畫
  • resizeMode 設置縮放模式
  • backgroundColor 背景顏色
  • borderColor 邊框顏色
  • borderWidth 邊框寬度
  • borderRadius 邊框圓角
  • overflow 設置圖片尺寸超過容器可以設置顯示或者隱藏(‘visible’,’hidden’)
  • tintColor 顏色設置
  • opacity 設置不透明度0.0(透明)-1.0(完全不透明)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章