編輯:關於 Android 程式設計
大家可能發現,原生的 Image 元件無法做到「等比放大後不失真」顯示。舉例來說,有一張 20×10 的圖片,要放進 40×30 的顯示區域:
1. cover 模式(預設):圖片放大為 60×30,再裁切為 40×30,會遺失部分內容。
2. contain 模式:圖片維持 20×10 解析度,四周留白。
3. stretch 模式:圖片被拉伸為 40×30,失去原始寬高比。
我們就是無法讓圖片放大為 40×20 後再顯示。接下來我們自訂一個元件 ImageEquallyEnlarge 來解決這個問題:
import React, { Component } from 'react'; import { Image } from 'react-native'; export default class ImageEquallyEnlarge extends Component { // 構造 constructor(props) { super(props); // 初始狀態 this.state = { //狀態機變量是一個style, 它將被用於定義顯示圖片的樣式 style: {} }; this.onImageLayout=this.onImageLayout.bind(this); } //此函數被掛接到組件的onLayout事件上, 當組件布局更新時, 此函數被調用 //此函數中計算新的寬度與高度並將其保存在組件的狀態機變量中 //event 對應的值為 : {nativeEvent: {layout: {x, y, width, height}}} onImageLayout(event) { let layout=event.nativeEvent.layout;//獲取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 } }); } // {...this.props} 是JSX語法, 意思是將ImageEquallyEnlarge組件收到的props透傳給Image組件 render(){ return( 這段程式碼其實沒有什麼特殊技巧:我們都知道在元件開始配置或配置改變時會呼叫 onLayout 方法,於是在其中取得 Image 元件的實際寬高,再依傳入的圖片真實寬高計算出合適的元件寬高,最後透過狀態機修改元件尺寸。
測試一下,修改 index.android.js 或 index.ios.js:
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, View, Image } from 'react-native'; //導入自定義組件 import ImageEquallyEnlarge from './ImageEquallyEnlarge'; class AwesomeProject extends Component { render() { return ( ); } } const styles = StyleSheet.create({ container: { backgroundColor: 'blue' }, imageStyle: { width: 240, height: 360, backgroundColor: 'red' }, image2Style: { width: 300, height: 460, backgroundColor: 'red' } }); AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);運行結果:

圖片原圖:

從背景顏色就能看出,圖片確實做到了等比放大而不失真。
Android 開發知識點總結:Activity 深入解析
進行 Android 專案開發時,無可避免會遇到 Activity 這個狀態組件,它描述了一個控制項、窗體等的當前狀態資訊。下面詳細介紹這個組件。 一、Activity
Android 各版本的 WebView 演進:從 WebKit 到 Chromium
前言 依據 Google 公布的 Android 各系統版本市占率數據,Android 4.0 及以上合計已接近九成,未來市面上的裝置幾乎都是 4.0 以上。因此本文聚焦
Android 任務堆疊與四種啟動模式圖解
Activity 的行為很大程度取決於它所在的任務堆疊(Task Stack)以及自身的啟動模式。這部分以理解為主,一旦掌握,頁面跳轉與返回行為的怪異現象都能解釋清楚。
Android ApiDemos 導入與運行步驟
Android SDK 自帶了大量示例,存放在 android-sdk/samples 目錄下,涵蓋了 Android 平台主要 API 的用法,是一份不可多得的學習資料