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

Android 自訂圓角 ImageView:PorterDuff 與自訂屬性完整實作

編輯:關於 Android 程式設計

直接上程式碼。

一、自訂 View 本體

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.ImageView;

import cn.dotcreate.tt.R;

public class RoundAngleImageView extends ImageView {

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

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

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

    public RoundAngleImageView(Context context) {
        super(context);
        init(context, null);
    }

    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);
            a.recycle();
        } else {
            // 程式碼建立時,手動依螢幕密度換算
            float density = context.getResources().getDisplayMetrics().density;
            roundWidth = (int) (roundWidth * density);
            roundHeight = (int) (roundHeight * density);
        }

        // 用來「挖掉」四個角的畫筆
        paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));

        // 用來把結果畫回真正的 canvas
        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);

        drawLiftUp(canvas2);
        drawRightUp(canvas2);
        drawLiftDown(canvas2);
        drawRightDown(canvas2);

        canvas.drawBitmap(bitmap, 0, 0, paint2);
        bitmap.recycle();
    }

    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);
    }
}

二、自訂屬性宣告

在 values 目錄下建立 attr.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="RoundAngleImageView">
        <attr name="roundWidth" format="dimension" />
        <attr name="roundHeight" format="dimension" />
    </declare-styleable>
</resources>

三、使用方式

先在根版面宣告自訂屬性的命名空間(xmlns:app="https://schemas.android.com/apk/res-auto"),接著就能像一般 View 一樣使用:

<cn.dotcreate.tt.ui.RoundAngleImageView
    android:id="@+id/headIV"
    android:layout_width="75dp"
    android:layout_height="75dp"
    android:layout_centerVertical="true"
    android:layout_marginLeft="2dp"
    app:roundWidth="10dp"
    app:roundHeight="10dp"
    android:src="@drawable/default_head_icon" />

效果如下:

四、原理與實務提醒

這個做法的核心是 PorterDuff.Mode.DST_OUT:先把原圖完整畫到一張暫存 Bitmap 上,再用「保留 dst、移除 src 重疊處」的 PorterDuff 模式,把四個角的部分擦掉,最後才把結果畫回真正的 Canvas。

值得注意的地方有幾點。第一,TypedArray 用完要 recycle。範例補上了 a.recycle(),這在記憶體受限的環境中是必要的習慣。

第二,每帧都配置 Bitmap 的代價很高。這個實作在 draw 中每次都 createBitmap 然後 recycle,若用在 ListView 的項目圖示上會造成明顯的效能問題與 GC 壓力。實務上更常見的替代方案有三種:

  • 用 CardView 或 MaterialCardView 的 cardCornerRadius,由官方元件處理圓角裁切。
  • 用 View.setClipToOutline(true) 搭配自訂 ViewOutlineProvider,讓系統直接裁切,不必另建 Bitmap。
  • 用 BitmapShader 搭配 Canvas.drawRoundRect,在繪製階段一次完成,避免中間產物。

第三,圓角寬高可獨立設定。把 roundWidth 與 roundHeight 設成不同值,就能做出橢圓角效果,這也是範例把兩者拆成獨立屬性的原因。若只想要正圓角,兩者設為相同即可。

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