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

徹底解決 android:background 背景圖被拉伸的問題

編輯:關於 Android 程式設計

先看 ImageView 裡 src 與 background 的差別:background 會依據元件給定的長寬進行拉伸,src 則保留原圖尺寸。src 是前景內容,background 是背景,兩者可以同時存在。另外要記住:scaleType 只對 src 生效,例如 ImageButton 就是用 android:scaleType 來控制圖片縮放方式。

問題重現

background 設定的圖片會被拉伸成 View 的長寬比例。舉例來說,一張 36x36 px 的圖標放在 xhdpi 資料夾,在 854x480(FWVGA,對應 hdpi)環境下,依

xhdpi : hdpi : mdpi : ldpi = 2 : 1.5 : 1 : 0.75

換算後實際尺寸應為 27x27。但把它放進一個 96px x 75px 的 LinearLayout:

<LinearLayout
    android:gravity="center"
    android:layout_width="96px"
    android:layout_height="75px" >

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/toolbar_bg"/>
</LinearLayout>

結果 ImageButton 實際是 33x27,寬度被硬撐開了,這顯然不是我們想要的。

解法一:程式碼中動態指定尺寸

LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(27, 27);
layout.addView(imageButton, layoutParam);

可行,但等於把數值硬編碼進程式碼,並不是理想做法。

解法二:用 XML Bitmap 包裝背景(推薦)

建立 toolbar_bg_bmp.xml:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@id/toolbar_bg_bmp"
    android:src="@drawable/toolbar_bg"
    android:tileMode="disabled"
    android:gravity="top" >
</bitmap>

使用方式:

imageButton.setBackgroundResource(R.drawable.toolbar_bg_bmp);

或者在 XML 中直接引用:

<ImageButton
    ...
    android:background="@drawable/toolbar_bg_bmp"
    ... />

如果背景有多種狀態(例如按下態),再包一層 selector 即可,參考 toolbar_bg_selector.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" >
        <bitmap
            android:src="@drawable/toolbar_bg_sel"
            android:tileMode="disabled"
            android:gravity="top" />
    </item>
    <item >
        <bitmap
            android:src="@drawable/toolbar_bg"
            android:tileMode="disabled"
            android:gravity="top" />
    </item>
</selector>

如此一來,不論走 setBackgroundResource() 還是 XML 的 android:background,都不會再出現拉伸的情況。

順帶一提,實務上更乾淨的做法是把 android:layout_width/height 寫成 wrap_content 搭配固定的 dp 尺寸,讓密度換算交給系統處理,能少掉不少這類硬編碼 px 造成的比例錯亂。

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