Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 將圖片裁切成圓形頭像的實作原理與程式碼

編輯:Android 開發實例

之前在論壇上找過不少把圖片裁成圓形的方法,效果都不太理想。後來因為業務需求要將頭像以圓形顯示,才自己動手做了一版,這裡記錄做法與思路。

裁剪策略

核心邏輯是依傳入圖片的高(height)與寬(width)決定要裁哪個方向,目標是先取出一個正方形區域,再把它裁成圓形:

若 width <= height,裁高度。寬度保持不變,高度從頂部取到與寬度相同的長度。

若 width > height,裁寬度。高度保持不變,寬度取圖片中央的區域。

不同業務對裁剪區域的要求可能不同(例如想取頂部而非中央),只要調整 src 矩形即可。

程式碼

/**
 * 轉換圖片成圓形
 * @param bitmap 傳入的 Bitmap 物件
 * @return 圓形 Bitmap
 */
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;
}

原理拆解

整個技巧可以分成三個動作。

第一步,在目的地畫布上畫一個圓角矩形,圓角半徑設為邊長的一半(roundPx),這樣四個圓角接起來剛好就是一個正圓。此時畫布上是「實心圓、其餘透明」。

第二步,設定 PorterDuffXfermode(Mode.SRC_IN)。這個混合模式的意思是:只保留來源圖(剛畫的圓)與目標圖重疊的部分,且以「已在畫布上的內容」為遮罩。因此後續畫上去的圖片,會被裁切成圓形。

第三步,用 drawBitmap(bitmap, src, dst, paint) 把原圖從 src 區域映射到 dst 區域畫上去,超出圓的部分就被丟掉了。

paint.setAntiAlias(true) 不能省,否則圓形邊緣會出現鋸齒。另外要留意順序:先畫遮罩形狀、再設 Xfermode、最後畫圖,顛倒就不會有效果。

幾個實務上的補充

這個方法每次都會建立新的 Bitmap,在 ListView 中大量使用時容易撐高記憶體。若效能吃緊,可以考慮改用 BitmapShader 搭配 Canvas.drawCircle(),不必複製位圖就能達到同樣效果。

另一個常見做法是直接寫一個繼承 ImageView 的自訂控制項,在 onDraw() 中用 clipPath 或 shader 裁切,這樣能避免反覆配置 Bitmap,也比較容易與 Glide、Picasso 這類載入框架搭配。

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