萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 圖片處理:高效生成圓角 Bitmap (避免重複創建、PorterDuffXfermode 裁剪)

優化版:單次 Bitmap 創建

/**
 * 產生圓角 Bitmap
 * @param source 原圖 (會被 recycle)
 * @param radius 圓角半徑 (px)
 * @return 圓角 Bitmap (ARGB_8888)
 */
public static Bitmap roundCorners(Bitmap source, float radius) {
    if (source == null || source.isRecycled()) return null;

    int w = source.getWidth();
    int h = source.getHeight();
    Bitmap output = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(output);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.WHITE); // 遮罩顏色不影響最終結果,只需不透明

    // 1. 畫圓角矩形遮罩
    canvas.drawRoundRect(new RectF(0, 0, w, h), radius, radius, paint);

    // 2. 設定 Xfermode:只保留「源圖」與「遮罩」相交部分 (SRC_IN)
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

    // 3. 繪製源圖,透過 Xfermode 裁剪成圓角
    canvas.drawBitmap(source, 0, 0, paint);

    // 4. 釋放原圖 (若調用者不再需要)
    source.recycle();

    return output;
}

原理圖解

  1. 建立空白輸出 Bitmap (畫布)。
  2. 畫白色圓角矩形 (遮罩層)。
  3. 設定 PorterDuff.Mode.SRC_IN:保留源圖 (Source) 與目標 (Destination/遮罩) 相交區域,其餘透明。
  4. 將源圖畫上畫布,即得到圓角效果。

對比:原版雙 Bitmap 版 (多一次創建與回收)

// 原版:創建 clipped 遮罩 -> 再創建 rounded -> 畫源圖 -> 畫遮罩 -> 回收兩個中間 Bitmap
Bitmap clipped = Bitmap.createBitmap(w, h, ARGB_8888);
Canvas c = new Canvas(clipped);
c.drawRoundRect(...);
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); // 反向邏輯
Bitmap rounded = Bitmap.createBitmap(w, h, ARGB_8888);
c = new Canvas(rounded);
c.drawBitmap(source, 0, 0, null);
c.drawBitmap(clipped, 0, 0, paint);
source.recycle(); clipped.recycle();
return rounded;

優化版減少 1 次 createBitmap、1 次 Canvas 創建、2 次 recycle,記憶體峰值降低 ~33%。

進階:圓形頭像 (radius = min(w,h)/2)

public static Bitmap toCircle(Bitmap source) {
    int size = Math.min(source.getWidth(), source.getHeight());
    return roundCorners(source, size / 2f);
}

現代替代:ShapeDrawable / MaterialShapeDrawable / Glide Transformation

  • XML 佈局:<ImageView android:background="@drawable/rounded_bg" /> 配合 shape + corners。
  • Glide:.transform(new RoundedCorners(radius)) 或 .circleCrop()。
  • Jetpack Compose:Image(..., contentScale = ContentScale.Crop, modifier = Modifier.clip(RoundedCornerShape(radius)))。
copyright © 萬盛學電腦網 all rights reserved