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

Android 將圖片裁剪為圓形圖片的實現原理與程式碼

編輯:關於 Android 程式設計

在製作頭像等場景時,我們常需要把圖片裁剪成圓形顯示。本文分享一個實用的做法:透過傳入圖片的高與寬來決定裁剪區域,最後用 Canvas 與 PorterDuff 模式把方圖變圓圖,並附上完整可運行的程式碼。

裁剪思路

核心在於先判斷寬高的關係,取出一個正方形區域:當 width <= height 時,裁高度,取寬度不變、從頂部到 width 長度的區域;當 width > height 時,裁寬度,取高度不變、寬度居中。不同業務對裁剪區域要求不同,可依需求調整。接著用圓角矩形搭配 PorterDuffXfermode 的 SRC_IN 模式,把方圖「套」進圓形遮罩中。

參考程式碼 如下:

/**
* 轉換圖片成圓形
* @param bitmap 傳入 Bitmap 對象
* @return
*/
public Bitmap toRoundBitmap(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float roundPx;
float left,top,right,bottom,dst_left,dst_top,dst_right,dst_bottom;
if (width <= height) {
roundPx = width / 2;
top = 0;
bottom = width;
left = 0;
right = width;
height = width;
dst_left = 0;
dst_top = 0;
dst_right = width;
dst_bottom = width;
} else {
roundPx = height / 2;
float clip = (width - height) / 2;
left = clip;
right = width - clip;
top = 0;
bottom = height;
width = height;
dst_left = 0;
dst_top = 0;
dst_right = height;
dst_bottom = height;
}
Bitmap output = Bitmap.createBitmap(width,
height, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect src = new Rect((int)left, (int)top, (int)right, (int)bottom);
final Rect dst = new Rect((int)dst_left, (int)dst_top, (int)dst_right, (int)dst_bottom);
final RectF rectF = new RectF(dst);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, src, dst, paint);
return output;
}

原理小結

整個流程可以拆成兩步:先用 drawRoundRect 畫出一個圓角(此處圓角半徑等於邊長一半,也就是正圓),再用 PorterDuffXfermode 的 SRC_IN 模式把原圖「填」進這個圓形範圍內。掌握這套 Canvas 合成技巧後,你就能輕鬆做出各種形狀的頭像裁剪效果。

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