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

Android 圖片處理:製作圓角圖片的優化寫法

編輯:關於 Android 程式設計

在 Android 中為圖片加上圓角是相當常見的需求。本文改良了流傳已久的一個圓角範例,主要優化點在於「少建立一次 Bitmap」,从而降低記憶體消耗。

優化後的版本

public static Bitmap roundCorners(final Bitmap source, final float radius) {
    int width = source.getWidth();
    int height = source.getHeight();

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(android.graphics.Color.WHITE);

    Bitmap clipped = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(clipped);
    canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius, paint);

    // 關鍵:以 SRC_IN 模式將原圖合成進圓角遮罩
    paint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(source, 0, 0, paint);

    source.recycle();
    return clipped;
}

原始版本

對照之下,原版的做法額外建立了一個 rounded Bitmap,並多了一次 clipped.recycle():

/**
 * Round the corners of a {@link Bitmap}
 * @param source 原始圖片
 * @param radius 圓角半徑
 * @return 帶有圓角的 bitmap
 */
public static Bitmap roundCorners(final Bitmap source, final float radius) {
    int width = source.getWidth();
    int height = source.getHeight();

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setColor(WHITE);

    Bitmap clipped = Bitmap.createBitmap(width, height, ARGB_8888);
    Canvas canvas = new Canvas(clipped);
    canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius, paint);

    paint.setXfermode(new PorterDuffXfermode(DST_IN));
    Bitmap rounded = Bitmap.createBitmap(width, height, ARGB_8888);
    canvas = new Canvas(rounded);
    canvas.drawBitmap(source, 0, 0, null);
    canvas.drawBitmap(clipped, 0, 0, paint);

    source.recycle();
    clipped.recycle();
    return rounded;
}

兩者的核心差異在於合成模式:原版使用 DST_IN 並額外建立一張位圖來承載結果;改良版則直接以 SRC_IN 把原圖合成到圓角遮罩上,省去一次 Bitmap 配置與回收,在處理大量圖片或低階裝置上能帶來明顯的效能優勢。

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