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

Android 三種實現圖片平鋪背景的方法

編輯:關於 Android 程式設計

在 Android 中實現圖片平鋪(repeating)背景效果,主要有三種做法:系統 API、XML 配置,以及自訂繪製。以下分別說明。

方法一:使用系統 API

透過 BitmapDrawable 的 setTileModeXY() 設定平鋪模式,並指定為 View 的背景:

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pic);
BitmapDrawable drawable = new BitmapDrawable(bitmap);
drawable.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
drawable.setDither(true);
view.setBackgroundDrawable(drawable);

方法二:使用 XML 配置

在 res/drawable/bg.xml 中以 <bitmap> 標籤設定 tileMode,較為簡潔:

<bitmap xmlns:android="https://schemas.android.com/apk/res/android"
    android:src="@drawable/img"
    android:tileMode="repeat" />

方法三:自訂繪製

若需要更靈活的控制(例如僅在水平或垂直方向平鋪到指定寬度),可自行以 Canvas 反覆貼圖:

public static Bitmap createRepeater(int width, Bitmap src) {
    int count = (width + src.getWidth() - 1) / src.getWidth();
    Bitmap bitmap = Bitmap.createBitmap(width, src.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    for (int idx = 0; idx < count; ++idx) {
        canvas.drawBitmap(src, idx * src.getWidth(), 0, null);
    }
    return bitmap;
}

三種方法的比較

  • 系統 API:寫法直接,適合在程式碼中動態設定背景,並可即時開啟 setDither(true) 改善漸層色帶。
  • XML 配置:最為簡潔,適合靜態、固定不變的平鋪背景,直接於版面或清單中引用即可。
  • 自訂繪製:彈性最高,可依需求計算平鋪的寬度或高度,適合需要精細控制的特殊場景,但會產生一張合成後的 Bitmap,較耗記憶體。

選擇哪一種取決於需求:追求簡單靜態就用 XML,需要動態切換就用系統 API,而追求特殊排版效果時則可考慮自訂繪製。

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