Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自定義控件:重寫 onMeasure 讓圖片永不變形,徹底搞定屏幕適配

編輯:關於 Android 程式設計

ImageView 的尷尬處境

圖片展示幾乎是每個應用的標配,無論是輪播圖還是廣告橫幅。我們通常希望圖片在橫向填滿父容器,這符合視覺習慣,但問題隨之而來:縱向高度該怎麼定?

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/recommend_39">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="描述文字信息......" />
    </ImageView>
</LinearLayout>

此時 ImageView 橫向填滿、縱向包裹內容,圖片並不會撐滿整個區域:

加上 android:scaleType="fitXY" 確實填滿了,但縱向被拉伸,圖片變形:

硬編高度(例如直接寫 132dp)在單一設備上湊效,但換個屏幕就露餡,不具通用性。

先補一堂單位課:px、dpi、dip

  • 分辨率:屏幕上的像素總數,如 480px × 800px。
  • dpi:每英寸的像素數量。同樣 1080×1920 分辨率,5 寸手機的 dpi 遠高於 9.7 寸平板。
  • dp/dip:密度無關像素,用來解決不同分辨率下顯示尺寸不一致的問題。它以 160dpi 設備為基準,1dp 在該設備上恰好等於 1px。

換算公式:

px  = dip * (dpi / 160)
dip = px / (dpi / 160)

舉個例子:兩台都是 5 寸屏,A 是 720×1280,B 是 1080×1920。直接擺一張 200×200 的圖,A 上佔了將近三分之一寬度,B 上卻不到五分之一。改用 dp 描述尺寸後,兩台設備的視覺大小就一致了。

動手算一次高度

示例圖片實際尺寸 828×314,寬高比約 2.43。模擬器寬度 480px,則應顯示高度為 480 / 2.43 ≈ 197.53px;該模擬器 dpi 為 240,換算成 dp 為 197.53 / (240/160) ≈ 131.68dp,取 132dp。

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="132dp"
    android:scaleType="fitXY"
    android:src="@drawable/recommend_39" />

比例正常了。但換成 Nexus 7(1200×1920,dpi 320)之後:

圖片又被拉長了。按公式重算,此時應為 1200 / 2.43 / (320/160) ≈ 246.91dp,而我們寫死的是 132dp。結論很明確:高度必須動態計算。

重寫 onMeasure,讓控件自己算高度

思路是寫一個 SmartImageView 繼承 ImageView,由它根據設備實際情況完成測量。首先要明確:自定義 View 在 measure() 執行之前拿不到自己的寬高。

package com.example.imageviewdemo;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * SmartImageView:根據給定的圖片比例自動調整寬高,解決拉伸變形與屏幕適配問題
 */
public class SmartImageView extends ImageView {

    /** 圖片寬高比 */
    private float ratio = 2.43f;

    public SmartImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public SmartImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SmartImageView(Context context) {
        super(context);
    }

    public void setRatio(float ratio) {
        this.ratio = ratio;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode  = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int width  = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
        int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingLeft() - getPaddingRight();

        if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY && ratio != 0.0f) {
            // 寬度確定、高度不確定:按比例推算高度
            height = (int) (width / ratio + 0.5f);
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        } else if (widthMode != MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY && ratio != 0.0f) {
            // 高度確定、寬度不確定:按比例推算寬度
            width = (int) (height * ratio + 0.5f);
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

幾個關鍵要點

1. MeasureSpec 的模式含義:布局中寫 fill_parent、具體數值,或在代碼裡設置 LayoutParams 的具體值,getMode 返回的都是 EXACTLY(填充父容器同樣是精確值);寫 wrap_content 則返回 AT_MOST。

2. 傳入的數值不一定是我們想要的值:EXACTLY 時它就是確切尺寸;AT_MOST 時它是上限,代表「不超過」。

3. 兩個分支的判斷依據:寬度確定時按比例算高度;高度確定時按比例算寬度。

4. 最後用 makeMeasureSpec 合成精確值,再交給 super.onMeasure 完成真正的測量。

使用方式

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.example.imageviewdemo.SmartImageView
        android:id="@+id/siv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:src="@drawable/recommend_39" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="描述文字信息......" />
</LinearLayout>
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SmartImageView siv = (SmartImageView) findViewById(R.id.siv);
        siv.setRatio(2.43f);
    }
}

此後無論手機、平板還是 TV,橫屏豎屏都能按正確比例呈現:

240×320 / 2.7 寸設備與 Nexus 7 1200×1920 設備對比。

Android TV(1920×1080)橫屏顯示效果。

最後一點補充:ratio 的來源可以是服務端下發,也可以自己讀取 Bitmap 的寬高算出來;除了調用 setRatio(),也可以封裝成自定義屬性直接在 XML 中指定。後續再聊聊 onLayout 的相關研究。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved