1. 程式人生 > >React Native 之 Image 等比例放大無丟失顯示

React Native 之 Image 等比例放大無丟失顯示

如果有一張 20*10 的圖片,要把它放入一個 40*30 的顯示區域內,我們可以做到:

contain 模式,圖片顯示解析度為20*10,四周都有空白;

cover模式,圖片放大為 60*30,然後切成 40*30,丟失部分圖片內容;

stretch 模式,圖片放大為 40*30,丟失原始的寬、高比。

實現自定義元件 ImageEquallyEnlarg.js

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

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

export default class ImageEqualEnlarge extends Component {

//ImageEqualEnlarge 元件的狀態機變數是一個style,它將被用於定義顯示圖片的樣式
constructor(props) { super(props); this.state = { style:{} }; } //宣告必須要有的圖片原始寬度與高度 static propTypes = { originalWidth:React.PropTypes.number.isRequired, originalHeight:React.PropTypes.number.isRequired } //此函式被掛接到元件的onLayout事件上,當元件被佈局時,此函式被呼叫 //在此函式中計算新的寬度與高度並將其儲存到元件的狀態機變數中
 onImageLayout(event){ let layout = event.nativeEvent.layout; if(layout.width<=this.props.originalWidth) return; if (layout.height<=this.props.originalHeight) return; let originalAspectRatio = this.props.originalWidth/this.props.originalHeight; let currentAspectRatio = layout.width/layout.height; if(originalAspectRatio===currentAspectRatio) return; if(originalAspectRatio > currentAspectRatio){ let newHeight = layout.width / originalAspectRatio; this.setState({ style:{ height:newHeight, } }); return; } let newWidth = layout.height*originalAspectRatio; this.setState({ style:{ width:newWidth, } }); } render() { return ( <Image {...this.props} style={[this.props.style,this.state.style]} onLayout ={this.onImageLayout.bind(this)} > </Image> ); } }
在index.android.js 呼叫 自定義元件 ImageEqualEnlarge  在資源本地引入 120*120 的影象
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

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

import ImageEqualEnlarge from './ImageEqualEnlarge.js' 

export default class ViewProject extends Component {

  render() {
    return (
      <View style={styles.container}>
        <ImageEqualEnlarge style={styles.imageStyle}
         source={require('./img/logo.png')}
         originalWidth={120}
         originalHeight={120}
        >
        </ImageEqualEnlarge>
        <ImageEqualEnlarge style={styles.image2Style}
         source={require('./img/logo.png')}
         originalWidth={120}
         originalHeight={120}
        >
        </ImageEqualEnlarge>
      
      </View>
    );
  }


}



const styles = StyleSheet.create({
  container: {
    backgroundColor:'blue',
  },
  imageStyle:{
    width:200,
    height:200,
    backgroundColor:'red',
  },
    image2Style:{
    width:300,
    height:200,
    backgroundColor:'red',
  }
 
});
AppRegistry.registerComponent('ViewProject', () => ViewProject);