/**
* 產生圓角 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;
}
PorterDuff.Mode.SRC_IN:保留源圖 (Source) 與目標 (Destination/遮罩) 相交區域,其餘透明。// 原版:創建 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%。
public static Bitmap toCircle(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
return roundCorners(source, size / 2f);
}
<ImageView android:background="@drawable/rounded_bg" /> 配合 shape + corners。.transform(new RoundedCorners(radius)) 或 .circleCrop()。Image(..., contentScale = ContentScale.Crop, modifier = Modifier.clip(RoundedCornerShape(radius)))。