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

自製圓角 ImageView:弧度可自訂的 RoundImageView 元件

編輯:關於 Android 開發

自製圓角 ImageView:弧度可自訂的 RoundImageView

設計稿上的頭像、封面圖常常需要圓角,而 ImageView 本身並沒有圓角屬性。最直覺的解法是自訂一個 View,在 draw() 中把原圖畫到一張暫存 Bitmap 上,再用 PorterDuffXfermode 搭配 DST_OUT 模式,把四個角「擦」掉。

關鍵在於四個圓角的 Path 怎麼畫:以左上角為例,從 (0, roundHeight) 出發,畫到原點,再往右到 (roundWidth, 0),最後用 arcTo 補上那段圓弧並閉合,這個封閉區域會被 DST_OUT 挖空,於是就形成圓角。

public class RoundImageView extends ImageView {

    private Paint paint;
    private int roundWidth = 50;
    private int roundHeight = 50;
    private Paint paint2;

    public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    /** 程式碼中動態設定圓角半徑 */
    public void SetRoundValue(float roundValue) {
        roundWidth = (int) roundValue;
        roundHeight = (int) roundValue;
    }

    public RoundImageView(Context context) {
        super(context, attrs == null ? null : attrs);
        init(context, null);
    }

    @SuppressLint("Recycle")
    private void init(Context context, AttributeSet attrs) {
        if (attrs != null) {
            // 從自訂屬性中讀取圓角尺寸
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundAngleImageView);
            roundWidth = a.getDimensionPixelSize(R.styleable.RoundAngleImageView_roundWidth, roundWidth);
            roundHeight = a.getDimensionPixelSize(R.styleable.RoundAngleImageView_roundHeight, roundHeight);
        } else {
            // 未指定時依螢幕密度換算,讓不同解析度下視覺一致
            float density = context.getResources().getDisplayMetrics().density;
            roundWidth = (int) (roundWidth * density);
            roundHeight = (int) (roundHeight * density);
        }

        // paint 負責挖空四個角
        paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));

        // paint2 正常作畫,不可帶 Xfermode
        paint2 = new Paint();
        paint2.setXfermode(null);
    }

    @Override
    public void draw(Canvas canvas) {
        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_8888);
        Canvas canvas2 = new Canvas(bitmap);
        super.draw(canvas2);            // 先把原圖畫到暫存 Bitmap
        drawLiftUp(canvas2);            // 左上角
        drawRightUp(canvas2);           // 右上角
        drawLiftDown(canvas2);          // 左下角
        drawRightDown(canvas2);         // 右下角
        canvas.drawBitmap(bitmap, 0, 0, paint2);
        bitmap.recycle();
        bitmap = null;
    }

    /** 左上角 */
    private void drawLiftUp(Canvas canvas) {
        Path path = new Path();
        path.moveTo(0, roundHeight);
        path.lineTo(0, 0);
        path.lineTo(roundWidth, 0);
        path.arcTo(new RectF(0, 0, roundWidth * 2, roundHeight * 2), -90, -90);
        path.close();
        canvas.drawPath(path, paint);
    }

    /** 左下角 */
    private void drawLiftDown(Canvas canvas) {
        Path path = new Path();
        path.moveTo(0, getHeight() - roundHeight);
        path.lineTo(0, getHeight());
        path.lineTo(roundWidth, getHeight());
        path.arcTo(new RectF(0, getHeight() - roundHeight * 2,
                0 + roundWidth * 2, getHeight()), 90, 90);
        path.close();
        canvas.drawPath(path, paint);
    }

    /** 右下角 */
    private void drawRightDown(Canvas canvas) {
        Path path = new Path();
        path.moveTo(getWidth() - roundWidth, getHeight());
        path.lineTo(getWidth(), getHeight());
        path.lineTo(getWidth(), getHeight() - roundHeight);
        path.arcTo(new RectF(getWidth() - roundWidth * 2, getHeight() - roundHeight * 2,
                getWidth(), getHeight()), 0, 90);
        path.close();
        canvas.drawPath(path, paint);
    }

    /** 右上角 */
    private void drawRightUp(Canvas canvas) {
        Path path = new Path();
        path.moveTo(getWidth(), roundHeight);
        path.lineTo(getWidth(), 0);
        path.lineTo(getWidth() - roundWidth, 0);
        path.arcTo(new RectF(getWidth() - roundWidth * 2, 0,
                getWidth(), 0 + roundHeight * 2), -90, 90);
        path.close();
        canvas.drawPath(path, paint);
    }
}

使用方式

XML 中直接當成 ImageView 使用,透過自訂屬性指定圓角大小:

<com.example.view.RoundImageView
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="120dp"
    android:layout_height="120dp"
    app:roundWidth="20dp"
    app:roundHeight="20dp" />

若想在程式碼中調整,呼叫 SetRoundValue(px) 後再 invalidate() 即可。記得 attrs.xml 中要先宣告 RoundAngleImageView 這個 declare-styleable,並包含 roundWidth 與 roundHeight 兩個屬性,否則會編譯失敗。

效能上的提醒

這種做法每次重繪都要建立一張與 View 同尺寸的 Bitmap,記憶體與效能成本都不低。若清單裡有大量圓角頭像,建議改用 BitmapShader 搭配 Canvas.drawRoundRect(),或直接使用 CardView、日後的 ImageView + ShapeableImageView,都能省下這層 Bitmap 拷貝。

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