1. 程式人生 > >React-Native開發五 React Native 的Image元件

React-Native開發五 React Native 的Image元件

1 Image元件介紹

RN中Image元件主要用於載入圖片,可載入靜態圖片,網路圖片,以及原生圖片,本地檔案系統中圖片資源
官方參考https://facebook.github.io/react-native/docs/image#resizemode

2 Image元件功能

載入圖片一般使用Image的source屬性
1 載入靜態圖片
靜態圖片是指js下的圖片資源,例如放在原始碼下的res的目錄
載入靜態圖片主要方式是:使用Image的source屬性,使用require來指定路徑

<Image source={require(image_path)}/>

注意,這裡的path一般是相對路徑,起點是當前js檔案所在的路徑

import React, { Component } from 'react';
import {Image, View} from "react-native";

const image_path1 = '../../res/img/qiqiu.jpg';

export default class ImageDemo extends Component{

    render(){
        return (
            <View>
                <Image source={require
(image_path1)}/> </View> ); } }

載入本地圖片資源可以不指定大小,預設以圖片資源大小。
效果如下:
這裡寫圖片描述
2 載入網路圖片
載入網路圖片資源主要用到source的uri屬性

<Image source={{uri:image_url}} style={{width:size,height:size}}/>

注意,載入網路圖片必須制定image的大小,否則無法載入

import React, { Component } from 'react';
import {Image, View} from "react-native"
; const image_path1 = '../../res/img/qiqiu.jpg'; const imgae_url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1531544047510&di=c76803f98e7e5e7b86ef403716ecd670&imgtype=0&src=http%3A%2F%2Fs8.sinaimg.cn%2Fmw690%2F006LDoUHzy7auXu0wVp67%26690'; export default class ImageDemo extends Component{ render(){ return ( <View> <Image source={require(image_path1)} }/> <Image source={{uri:imgae_url}} style={{width:200,height:200,margin:5}}/> </View> ); } }

效果如下:
這裡寫圖片描述

3 載入Android IOS原生圖片
載入原生圖片是指能載入Android中drawable中的圖片,也能載入IOS中的圖片,這裡以一張在Android中drawable中qiqiu.jpg

<Image source={{uri:image_native_path}} style={{width:100,height:100}}/>

注意,載入原生圖片也必須制定大小,並且需要重新執行react-native run android

import React, { Component } from 'react';
import {Image, View} from "react-native";

const image_path1 = '../../res/img/qiqiu.jpg';
const imgae_url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1531544047510&di=c76803f98e7e5e7b86ef403716ecd670&imgtype=0&src=http%3A%2F%2Fs8.sinaimg.cn%2Fmw690%2F006LDoUHzy7auXu0wVp67%26690';
const image_native_1 = 'qiqiu';

export default class ImageDemo extends Component{

    render(){
        return (
            <View>
                <Image source={require(image_path1)} />
                <Image source={{uri:imgae_url}} style={{width:200,height:200,margin:5}}/>
                <Image source={{uri:image_native_1}} style={{width:100,height:100,margin:5}}/>
            </View>
        );
    }

}

效果如下:
這裡寫圖片描述

3 Image圖片載入技巧

1 圖片縮放resizeMode
表示圖片縮放模式
cover: 均勻縮放影象(保持影象的縱橫比),使影象的尺寸(寬度和高度)等於或大於檢視的相應尺寸(減去填充)。
contain: 均勻縮放影象(保持影象的縱橫比),使影象的尺寸(寬度和高度)等於或小於檢視的相應尺寸(減去填充)。
stretch: 獨立縮放寬度和高度,這可能會改變圖片的寬高比
repeat: 重複影象以覆蓋檢視的框架。 影象將保持其大小和縱橫比,除非它大於檢視,在這種情況下,它將被均勻縮小以使其包含在檢視中。IOS支援,Android不支援
center: 使影象沿兩個維度居中。 如果影象大於檢視,請將其均勻縮小以使其包含在檢視中。

預設屬性是cover