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

Android 自訂 View 實作圓形與圓角 ImageView(含邊框與 XML 屬性)

編輯:關於 Android 程式設計

一、問題出在哪?

這個需求來自 App 開發中極常見的場景——使用者頭像要顯示成圓形:

二、最直覺的想法,以及它為何不行

第一個念頭很機靈:切一張中央圓形透明、四周與底色相同、尺寸與頭像一致的蒙板圖,蓋在頭像上不就好了?

在背景是純色的前提下,這招確實能解決問題。但背景一旦不單純就麻煩了:

在這種不規則背景下會冒出兩個問題。第一,背景圖通常會依手機寬度縮放,而頭像是固定 dp 寬高,固定的蒙板圖根本無法保證在不同機型上都與背景圖案對齊。第二,非純色背景下,哪天想調整頭像位置就得重做一張蒙板圖,維護成本太高。

既然頭像素材本身是方的,那就讓 ImageView 圓起來吧。

三、動手實作

基本思路是自訂一個 ImageView,覆寫 onDraw() 畫出圓形裁切後的圖片:

public class ImageViewPlus extends ImageView {
    private Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Bitmap mRawBitmap;
    private BitmapShader mShader;
    private Matrix mMatrix = new Matrix();

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

    @Override
    protected void onDraw(Canvas canvas) {
        Bitmap rawBitmap = getBitmap(getDrawable());
        if (rawBitmap != null) {
            int viewWidth = getWidth();
            int viewHeight = getHeight();
            int viewMinSize = Math.min(viewWidth, viewHeight);
            float dstWidth = viewMinSize;
            float dstHeight = viewMinSize;

            if (mShader == null || !rawBitmap.equals(mRawBitmap)) {
                mRawBitmap = rawBitmap;
                mShader = new BitmapShader(mRawBitmap, TileMode.CLAMP, TileMode.CLAMP);
            }
            if (mShader != null) {
                mMatrix.setScale(dstWidth / rawBitmap.getWidth(), dstHeight / rawBitmap.getHeight());
                mShader.setLocalMatrix(mMatrix);
            }
            mPaintBitmap.setShader(mShader);

            float radius = viewMinSize / 2.0f;
            canvas.drawCircle(radius, radius, radius, mPaintBitmap);
        } else {
            super.onDraw(canvas);
        }
    }

    private Bitmap getBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof ColorDrawable) {
            Rect rect = drawable.getBounds();
            int width = rect.right - rect.left;
            int height = rect.bottom - rect.top;
            int color = ((ColorDrawable) drawable).getColor();
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawARGB(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color));
            return bitmap;
        } else {
            return null;
        }
    }
}

拆解一下:canvas.drawCircle 決定成品是圓形,而圓形裡的內容則由 mPaintBitmap.setShader 負責。

BitmapShader 需要指定 Bitmap 的填滿方式(CLAMP 拉伸邊緣、MIRROR 鏡像、REPEAT 整圖重複)。這裡其實設成哪個都不重要,因為我們真正想要的是把 Bitmap 等比縮放到與 ImageView 同大,而非上述三種預設行為。所以別忘了 mMatrix.setScale 與 mShader.setLocalMatrix 要成套使用,才能把圖片縮放到正確尺寸。

另外 getBitmap() 額外處理了 ColorDrawable:直接把 android:src 設為顏色時,drawable 並非 BitmapDrawable,若不處理就會畫不出東西,因此這裡手動依色值生成一張同尺寸的 Bitmap。

四、加個邊框

如果想幫圓形頭像加上邊框:

public class ImageViewPlus extends ImageView {
    private Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Paint mPaintBorder = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Bitmap mRawBitmap;
    private BitmapShader mShader;
    private Matrix mMatrix = new Matrix();
    private float mBorderWidth = dip2px(15);
    private int mBorderColor = 0xFF0080FF;

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

    @Override
    protected void onDraw(Canvas canvas) {
        Bitmap rawBitmap = getBitmap(getDrawable());
        if (rawBitmap != null) {
            int viewWidth = getWidth();
            int viewHeight = getHeight();
            int viewMinSize = Math.min(viewWidth, viewHeight);
            float dstWidth = viewMinSize;
            float dstHeight = viewMinSize;

            if (mShader == null || !rawBitmap.equals(mRawBitmap)) {
                mRawBitmap = rawBitmap;
                mShader = new BitmapShader(mRawBitmap, TileMode.CLAMP, TileMode.CLAMP);
            }
            if (mShader != null) {
                mMatrix.setScale((dstWidth - mBorderWidth * 2) / rawBitmap.getWidth(),
                                 (dstHeight - mBorderWidth * 2) / rawBitmap.getHeight());
                mShader.setLocalMatrix(mMatrix);
            }
            mPaintBitmap.setShader(mShader);

            mPaintBorder.setStyle(Paint.Style.STROKE);
            mPaintBorder.setStrokeWidth(mBorderWidth);
            mPaintBorder.setColor(mBorderColor);

            float radius = viewMinSize / 2.0f;
            canvas.drawCircle(radius, radius, radius - mBorderWidth / 2.0f, mPaintBorder);
            canvas.translate(mBorderWidth, mBorderWidth);
            canvas.drawCircle(radius - mBorderWidth, radius - mBorderWidth, radius - mBorderWidth, mPaintBitmap);
        } else {
            super.onDraw(canvas);
        }
    }

    private Bitmap getBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof ColorDrawable) {
            Rect rect = drawable.getBounds();
            int width = rect.right - rect.left;
            int height = rect.bottom - rect.top;
            int color = ((ColorDrawable) drawable).getColor();
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawARGB(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color));
            return bitmap;
        } else {
            return null;
        }
    }

    private int dip2px(int dipVal) {
        float scale = getResources().getDisplayMetrics().density;
        return (int) (dipVal * scale + 0.5f);
    }
}

加邊框的本質,就是用實心純色的 Paint 畫一個圓環,再把頭像畫在裡面。有三個細節容易踩坑:

1、圓框的半徑不是 radius,而是 radius - mBorderWidth / 2.0f。想像手拿筆畫線,線條其實落在往內縮半個筆寬的位置,只不過它很粗。

2、ImageView 尺寸不變,但頭像實際可用面積變小了,所以 mMatrix.setScale 時要把兩側邊框寬度都扣掉。

3、畫頭像時不能直接寫 canvas.drawCircle(radius, radius, radius - mBorderWidth, mPaintBitmap),否則你會發現頭像右側與下緣被拉長了。

原因在於 Paint 預設以左上角為基準開始繪製,此時頭像的實際區域偏向左上角,而超出的部分(圓形的右側與下方)自然被 TileMode.CLAMP 沿邊緣拉伸。解法是先 canvas.translate 挪動座標系,再調整圓心位置,把頭像畫進正確的區域。

五、支援 XML 屬性配置

邊框寬度與顏色若能在 XML 裡設定會方便許多。基本上有兩條路:一是加上 setter 再由外部呼叫並 invalidate() 重繪;二是在 XML 中支援自訂屬性。這裡重點說第二種。

首先在 res\values 下定義屬性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="borderColor" format="color" />
    <attr name="borderWidth" format="dimension" />
    <declare-styleable name="ImageViewPlus">
        <attr name="borderColor" />
        <attr name="borderWidth" />
    </declare-styleable>
</resources>

接著在建構子中讀取:

private static final int DEFAULT_BORDER_COLOR = Color.TRANSPARENT;
private static final int DEFAULT_BORDER_WIDTH = 0;

public ImageViewPlus(Context context, AttributeSet attrs) {
    super(context, attrs);
    // 取 xml 檔中設定的參數
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImageViewPlus);
    mBorderColor = ta.getColor(R.styleable.ImageViewPlus_borderColor, DEFAULT_BORDER_COLOR);
    mBorderWidth = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_borderWidth, dip2px(DEFAULT_BORDER_WIDTH));
    ta.recycle();
}

佈局中的用法如下,記得在根節點宣告自訂命名空間:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:snser="https://schemas.android.com/apk/res/cc.snser.imageviewplus"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/wallpaper"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <cc.snser.imageviewplus.ImageViewPlus
        android:id="@+id/imgplus"
        android:layout_width="200dp"
        android:layout_height="300dp"
        android:layout_marginBottom="50dp"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:src="@drawable/img_square"
        snser:borderColor="#FF0080FF"
        snser:borderWidth="15dp" />
</RelativeLayout>

別忘了呼叫 ta.recycle(),否則會造成資源不必要的佔用。

六、進而支援圓角

搞定圓形與邊框之後,要做出圓角的 ImageView 就更簡單了:

原理完全一致,把 canvas.drawCircle 換成 canvas.drawRoundRect 即可:

public class ImageViewPlus extends ImageView {
    /** 原生的 android.widget.ImageView */
    public static final int TYPE_NONE = 0;
    /** 圓形 */
    public static final int TYPE_CIRCLE = 1;
    /** 圓角矩形 */
    public static final int TYPE_ROUNDED_RECT = 2;

    private static final int DEFAULT_TYPE = TYPE_NONE;
    private static final int DEFAULT_BORDER_COLOR = Color.TRANSPARENT;
    private static final int DEFAULT_BORDER_WIDTH = 0;
    private static final int DEFAULT_RECT_ROUND_RADIUS = 0;

    private int mType;
    private int mBorderColor;
    private int mBorderWidth;
    private int mRectRoundRadius;

    private Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Paint mPaintBorder = new Paint(Paint.ANTI_ALIAS_FLAG);
    private RectF mRectBorder = new RectF();
    private RectF mRectBitmap = new RectF();
    private Bitmap mRawBitmap;
    private BitmapShader mShader;
    private Matrix mMatrix = new Matrix();

    public ImageViewPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 取 xml 檔中設定的參數
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImageViewPlus);
        mType = ta.getInt(R.styleable.ImageViewPlus_type, DEFAULT_TYPE);
        mBorderColor = ta.getColor(R.styleable.ImageViewPlus_borderColor, DEFAULT_BORDER_COLOR);
        mBorderWidth = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_borderWidth, dip2px(DEFAULT_BORDER_WIDTH));
        mRectRoundRadius = ta.getDimensionPixelSize(R.styleable.ImageViewPlus_rectRoundRadius, dip2px(DEFAULT_RECT_ROUND_RADIUS));
        ta.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Bitmap rawBitmap = getBitmap(getDrawable());
        if (rawBitmap != null && mType != TYPE_NONE) {
            int viewWidth = getWidth();
            int viewHeight = getHeight();
            int viewMinSize = Math.min(viewWidth, viewHeight);
            float dstWidth = mType == TYPE_CIRCLE ? viewMinSize : viewWidth;
            float dstHeight = mType == TYPE_CIRCLE ? viewMinSize : viewHeight;
            float halfBorderWidth = mBorderWidth / 2.0f;
            float doubleBorderWidth = mBorderWidth * 2;

            if (mShader == null || !rawBitmap.equals(mRawBitmap)) {
                mRawBitmap = rawBitmap;
                mShader = new BitmapShader(mRawBitmap, TileMode.CLAMP, TileMode.CLAMP);
            }
            if (mShader != null) {
                mMatrix.setScale((dstWidth - doubleBorderWidth) / rawBitmap.getWidth(),
                                 (dstHeight - doubleBorderWidth) / rawBitmap.getHeight());
                mShader.setLocalMatrix(mMatrix);
            }
            mPaintBitmap.setShader(mShader);

            mPaintBorder.setStyle(Paint.Style.STROKE);
            mPaintBorder.setStrokeWidth(mBorderWidth);
            mPaintBorder.setColor(mBorderWidth > 0 ? mBorderColor : Color.TRANSPARENT);

            if (mType == TYPE_CIRCLE) {
                float radius = viewMinSize / 2.0f;
                canvas.drawCircle(radius, radius, radius - halfBorderWidth, mPaintBorder);
                canvas.translate(mBorderWidth, mBorderWidth);
                canvas.drawCircle(radius - mBorderWidth, radius - mBorderWidth, radius - mBorderWidth, mPaintBitmap);
            } else if (mType == TYPE_ROUNDED_RECT) {
                mRectBorder.set(halfBorderWidth, halfBorderWidth, dstWidth - halfBorderWidth, dstHeight - halfBorderWidth);
                mRectBitmap.set(0.0f, 0.0f, dstWidth - doubleBorderWidth, dstHeight - doubleBorderWidth);
                float borderRadius = mRectRoundRadius - halfBorderWidth > 0.0f ? mRectRoundRadius - halfBorderWidth : 0.0f;
                float bitmapRadius = mRectRoundRadius - mBorderWidth > 0.0f ? mRectRoundRadius - mBorderWidth : 0.0f;
                canvas.drawRoundRect(mRectBorder, borderRadius, borderRadius, mPaintBorder);
                canvas.translate(mBorderWidth, mBorderWidth);
                canvas.drawRoundRect(mRectBitmap, bitmapRadius, bitmapRadius, mPaintBitmap);
            }
        } else {
            super.onDraw(canvas);
        }
    }

    private int dip2px(int dipVal) {
        float scale = getResources().getDisplayMetrics().density;
        return (int) (dipVal * scale + 0.5f);
    }

    private Bitmap getBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof ColorDrawable) {
            Rect rect = drawable.getBounds();
            int width = rect.right - rect.left;
            int height = rect.bottom - rect.top;
            int color = ((ColorDrawable) drawable).getColor();
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawARGB(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color));
            return bitmap;
        } else {
            return null;
        }
    }
}

用法:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:snser="https://schemas.android.com/apk/res/cc.snser.imageviewplus"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/wallpaper"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <cc.snser.imageviewplus.ImageViewPlus
        android:id="@+id/imgplus"
        android:layout_width="200dp"
        android:layout_height="300dp"
        android:layout_marginBottom="50dp"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:src="@drawable/img_rectangle"
        snser:type="rounded_rect"
        snser:borderColor="#FF0080FF"
        snser:borderWidth="10dp"
        snser:rectRoundRadius="30dp" />
</RelativeLayout>

屬性定義:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="type">
        <enum name="none" value="0" />
        <enum name="circle" value="1" />
        <enum name="rounded_rect" value="2" />
    </attr>
    <attr name="borderColor" format="color" />
    <attr name="borderWidth" format="dimension" />
    <attr name="rectRoundRadius" format="dimension" />
    <declare-styleable name="ImageViewPlus">
        <attr name="type" />
        <attr name="borderColor" />
        <attr name="borderWidth" />
        <attr name="rectRoundRadius" />
    </declare-styleable>
</resources>

把 type 定義成 enum 而非單純的整數,的好處是 XML 裡能直接寫 rounded_rect 這樣具語意的字串,可讀性明顯提升。此外這版刻意保留 TYPE_NONE 作為預設值,讓未指定 type 時退回原生行為,不會影響既有頁面。

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