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

自定義控件三部曲之繪圖篇(十七)——為 Bitmap 加上自訂顏色陰影並封裝控件

編輯:關於 Android 程式設計

上一篇講了如何為控件加上陰影,但用 setShadowLayer 幫 Bitmap 加陰影時,沒辦法指定陰影顏色。這篇我們用自定義屬性把「彩色陰影」封裝成一個真正可用的控件。本篇資訊量偏大、難度偏高,建議慢慢讀。

一、用 BlurMaskFilter 為圖片造出指定顏色的陰影

setShadowLayer 產生的陰影,本質是原圖形的副本加上邊緣發光。先拆開它的形成過程(假設畫筆是灰色):它會先產生一個與原圖形形狀相同的灰色副本,接著對這個灰色副本套用 BlurMaskFilter 使其內外發光,最後再偏移一段距離繪製——陰影就出現了。

那我們完全可以照這個思路自己走一遍:

1. 畫出一個與原圖同尺寸的灰色圖形;
2. 對它套用 BlurMaskFilter 使其內外發光;
3. 把原圖偏移一段距離蓋上去。

1. 畫出同尺寸的灰色圖形

關鍵在於:canvas.drawBitmap(bitmap, src, dst, paint) 裡的畫筆顏色,對輸出的像素顏色是沒有影響的,原圖長什麼樣,畫出來就是什麼樣。所以我們需要的不是「變色」,而是一張尺寸相同、Alpha 通道一致的空白圖,顏色完全交給畫筆決定。

Bitmap 已經內建了這個能力:

public Bitmap extractAlpha();

extractAlpha() 會新建一張空白圖,每個像素的 Alpha 值與原圖一致並作為結果返回;至於實際顏色,則在 canvas.drawBitmap 時由傳入的 paint 決定。

(1)extractAlpha() 使用示例

拿一張 PNG 來試,圖中有一隻貓和一隻狗,其餘部分全透明。

接著用 extractAlpha() 分別畫出紅色和綠色版本:

public class ExtractAlphaView extends View {
    private Paint mPaint;
    private Bitmap mBitmap, mAlphaBmp;

    public ExtractAlphaView(Context context) {
        super(context);
        init();
    }

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

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

    private void init() {
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        mPaint = new Paint();
        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.blog12);
        mAlphaBmp = mBitmap.extractAlpha();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = 200;
        int height = width * mAlphaBmp.getHeight() / mAlphaBmp.getWidth();
        mPaint.setColor(Color.RED);
        canvas.drawBitmap(mAlphaBmp, null, new Rect(0, 0, width, height), mPaint);
        mPaint.setColor(Color.GREEN);
        canvas.drawBitmap(mAlphaBmp, null, new Rect(0, height, width, 2 * height), mPaint);
    }
}

init() 裡第一件事是關閉硬體加速,這幾乎是自定義控件的標準動作,能避免一堆「功能莫名失效」的問題,建議每次都加上。第二件事就是用 extractAlpha() 生成只有透明度的空白圖。

onDraw() 裡只是把畫筆顏色在紅、綠之間切換,然後各畫一次 mAlphaBmp。因為此時的顏色完全由畫筆決定,所以輸出分別是紅色與綠色。

2. 對灰色圖形套用 BlurMaskFilter 使其內外發光

只要加上 maskFilter 就有發光效果:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    int width = 200;
    int height = width * mAlphaBmp.getHeight() / mAlphaBmp.getWidth();
    mPaint.setColor(Color.RED);
    mPaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.NORMAL));
    canvas.drawBitmap(mAlphaBmp, null, new Rect(0, 0, width, height), mPaint);
    mPaint.setColor(Color.GREEN);
    canvas.drawBitmap(mAlphaBmp, null, new Rect(0, height, width, 2 * height), mPaint);
}

唯一的新增就是這一行:mPaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.NORMAL));

3. 偏移原圖形一段距離畫出來

先把陰影畫好,再把原圖蓋上去,注意陰影要相對原圖偏移。

public class ExtractAlphaView extends View {
    private Paint mPaint;
    private Bitmap mBitmap, mAlphaBmp;

    public ExtractAlphaView(Context context) {
        super(context);
        init();
    }

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

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

    private void init() {
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        mPaint = new Paint();
        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.blog12);
        mAlphaBmp = mBitmap.extractAlpha();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = 200;
        int height = width * mAlphaBmp.getHeight() / mAlphaBmp.getWidth();

        // 繪製陰影
        mPaint.setColor(Color.RED);
        mPaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.NORMAL));
        canvas.drawBitmap(mAlphaBmp, null, new Rect(10, 10, width, height), mPaint);
        mPaint.setColor(Color.GREEN);
        canvas.drawBitmap(mAlphaBmp, null, new Rect(10, height + 10, width, 2 * height), mPaint);

        // 繪製原圖像
        mPaint.setMaskFilter(null);
        canvas.drawBitmap(mBitmap, null, new Rect(0, 0, width, height), mPaint);
        canvas.drawBitmap(mBitmap, null, new Rect(0, height, width, 2 * height), mPaint);
    }
}

兩個細節:畫原圖之前必須用 mPaint.setMaskFilter(null) 把發光效果拿掉,只有陰影需要發光;另外陰影偏移了 10 個像素。

二、封裝成控件

上面的 demo 只是一小步。真正的目標是封裝出一個控件,支援:

· 由使用者指定圖片內容
· 由使用者指定偏移距離
· 由使用者指定陰影顏色與模糊程度
· 支援 wrap_content 自適應大小

1. 定義自定義屬性

關於自定義屬性的定義與提取方式,可以參考《PullScrollView 詳解(一)——自定義控件屬性》,這裡直接假設你已經掌握。我們需要四個屬性對應四個需求,另外仿照 setShadowLayer 補上 dx / dy / radius。

attr.xml:

<resources>
    <declare-styleable name="BitmapShadowView">
        <attr name="src" format="reference" />
        <attr name="shadowDx" format="dimension" />
        <attr name="shadowDy" format="dimension" />
        <attr name="shadowColor" format="color" />
        <attr name="shadowRadius" format="float" />
    </declare-styleable>
</resources>

布局中使用(main.xml):

<linearlayout
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res/com.harvic.BlogBitmapShadow">

    <com.harvic.blogbitmapshadow.bitmapshadowview
        android:layout_gravity="center_horizontal"
        android:layout_height="200dp"
        android:layout_width="200dp"
        app:shadowcolor="@android:color/holo_red_dark"
        app:shadowdx="10"
        app:shadowdy="10"
        app:shadowradius="10.0"
        app:src="@drawable/blog12">
    </com.harvic.blogbitmapshadow.bitmapshadowview>
</linearlayout>

接下來看代碼中如何提取這些屬性並繪製陰影:

public class BitmapShadowView extends View {
    private Paint mPaint;
    private Bitmap mBmp, mShadowBmp;
    private int mDx = 10, mDy = 10;
    private float mRadius = 0;
    private int mShadowColor;

    public BitmapShadowView(Context context, AttributeSet attrs) throws Exception {
        super(context, attrs);
        init(context, attrs);
    }

    public BitmapShadowView(Context context, AttributeSet attrs, int defStyle) throws Exception {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) throws Exception {
        setLayerType(LAYER_TYPE_SOFTWARE, null);

        // 提取屬性定義
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BitmapShadowView);
        int BitmapID = typedArray.getResourceId(R.styleable.BitmapShadowView_src, -1);
        if (BitmapID == -1) {
            throw new Exception("BitmapShadowView 需要定義 Src 屬性,而且必須是圖像");
        }
        mBmp = BitmapFactory.decodeResource(getResources(), BitmapID);
        mDx = typedArray.getInt(R.styleable.BitmapShadowView_shadowDx, 0);
        mDy = typedArray.getInt(R.styleable.BitmapShadowView_shadowDy, 0);
        mRadius = typedArray.getFloat(R.styleable.BitmapShadowView_shadowRadius, 0);
        mShadowColor = typedArray.getColor(R.styleable.BitmapShadowView_shadowColor, Color.BLACK);
        typedArray.recycle();

        // 其它初始化
        mPaint = new Paint();
        mShadowBmp = mBmp.extractAlpha();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth() - mDx;
        int height = width * mBmp.getHeight() / mBmp.getWidth();

        // 繪製陰影
        mPaint.setColor(mShadowColor);
        mPaint.setMaskFilter(new BlurMaskFilter(mRadius, BlurMaskFilter.Blur.NORMAL));
        canvas.drawBitmap(mShadowBmp, null, new Rect(mDx, mDy, width, height), mPaint);

        // 繪製原圖像
        mPaint.setMaskFilter(null);
        canvas.drawBitmap(mBmp, null, new Rect(0, 0, width, height), mPaint);
    }
}

初始化時,因為做陰影離不開圖片,所以對 src 加了容錯:取不到就拋異常直接中止,讓開發者在寫代碼階段就發現問題,而不是等上線後才發現少了 bitmap。

onDraw 中的寬度刻意扣掉 mDx,是為了把陰影的位置留出來;高度則依原圖寬高比換算。原圖畫在左上角 (0, 0),陰影畫在 (mDx, mDy)。

目前雖然能自定義屬性,但使用時必須強制指定固定寬高或 fill_parent,這顯然不合理。

2. 支援 wrap_content 自適應寬高

要做到自適應,只需要重寫 onMeasure()(onMeasure 的原理可參考《FlowLayout 詳解(一)——onMeasure() 與 onLayout()》):

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
    int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
    int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
    int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);
    int width = mBmp.getWidth();
    int height = mBmp.getHeight();
    setMeasuredDimension(
        (measureWidthMode == MeasureSpec.EXACTLY) ? measureWidth : width,
        (measureHeightMode == MeasureSpec.EXACTLY) ? measureHeight : height);
}

也就是說,當使用者指定 wrap_content 時,就用圖片本身的寬高作為控件尺寸。完整代碼如下:

public class BitmapShadowView extends View {
    private Paint mPaint;
    private Bitmap mBmp, mShadowBmp;
    private int mDx = 10, mDy = 10;
    private float mRadius = 0;
    private int mShadowColor;

    public BitmapShadowView(Context context, AttributeSet attrs) throws Exception {
        super(context, attrs);
        init(context, attrs);
    }

    public BitmapShadowView(Context context, AttributeSet attrs, int defStyle) throws Exception {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) throws Exception {
        setLayerType(LAYER_TYPE_SOFTWARE, null);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BitmapShadowView);
        int BitmapID = typedArray.getResourceId(R.styleable.BitmapShadowView_src, -1);
        if (BitmapID == -1) {
            throw new Exception("BitmapShadowView 需要定義 Src 屬性,而且必須是圖像");
        }
        mBmp = BitmapFactory.decodeResource(getResources(), BitmapID);
        mDx = typedArray.getInt(R.styleable.BitmapShadowView_shadowDx, 0);
        mDy = typedArray.getInt(R.styleable.BitmapShadowView_shadowDy, 0);
        mRadius = typedArray.getFloat(R.styleable.BitmapShadowView_shadowRadius, 0);
        mShadowColor = typedArray.getColor(R.styleable.BitmapShadowView_shadowColor, Color.BLACK);
        typedArray.recycle();

        mPaint = new Paint();
        mShadowBmp = mBmp.extractAlpha();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
        int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
        int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
        int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);
        int width = mBmp.getWidth();
        int height = mBmp.getHeight();
        setMeasuredDimension(
            (measureWidthMode == MeasureSpec.EXACTLY) ? measureWidth : width,
            (measureHeightMode == MeasureSpec.EXACTLY) ? measureHeight : height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth() - mDx;
        int height = width * mBmp.getHeight() / mBmp.getWidth();

        mPaint.setColor(mShadowColor);
        mPaint.setMaskFilter(new BlurMaskFilter(mRadius, BlurMaskFilter.Blur.NORMAL));
        canvas.drawBitmap(mShadowBmp, null, new Rect(mDx, mDy, width, height), mPaint);

        mPaint.setMaskFilter(null);
        canvas.drawBitmap(mBmp, null, new Rect(0, 0, width, height), mPaint);
    }
}

改用 wrap_content 的布局寫法:

<linearlayout
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res/com.harvic.BlogBitmapShadow">

    <com.harvic.blogbitmapshadow.bitmapshadowview
        android:layout_gravity="center_horizontal"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        app:shadowcolor="@android:color/holo_red_dark"
        app:shadowdx="10"
        app:shadowdy="10"
        app:shadowradius="10.0"
        app:src="@drawable/blog12">
    </com.harvic.blogbitmapshadow.bitmapshadowview>

    <button
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="test BTN" />
</linearlayout>

想要灰色陰影,只要改一下 shadowColor(為了方便看陰影,我把 Activity 背景改成白色):

<linearlayout
    android:background="@android:color/white"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res/com.harvic.BlogBitmapShadow">

    <com.harvic.blogbitmapshadow.bitmapshadowview
        android:layout_gravity="center_horizontal"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        app:shadowcolor="@android:color/darker_gray"
        app:shadowdx="10"
        app:shadowdy="10"
        app:shadowradius="10.0"
        app:src="@drawable/blog12">
    </com.harvic.blogbitmapshadow.bitmapshadowview>

    <button
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="test BTN" />
</linearlayout>

封裝到此完成。最後補一個細節:View 一共有三個構造函數,我只實作了帶 AttributeSet 的兩個,還有一個沒寫:

public BitmapShadowView(Context context) {
    super(context);
}

從 XML 生成控件時呼叫的是帶 AttributeSet 的版本,而純代碼 new 出來時呼叫的是只有 context 的版本。如果需要支援代碼建立,記得補上這個構造函數,並提供對外的 setter 讓外部設定各項屬性。這部分就留給讀者自行補完,讓控件更完整。

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