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

Android Paint 之 ColorFilter 詳解:三大子類與矩陣調色原理

編輯:關於 Android 程式設計

之前講 Paint 詳解時,setColorFilter(ColorFilter filter) 這個方法沒有展開,今天來補上。ColorFilter 在 Android 中共有三個子類:ColorMatrixColorFilter、LightingColorFilter、PorterDuffColorFilter。

一、ColorMatrixColorFilter

它的構造方法很簡單,一個接收 ColorMatrix 對象,一個直接接收長度 20 的 float 陣列:

public ColorMatrixColorFilter(ColorMatrix matrix) {
    mMatrix.set(matrix);
    update();
}

public ColorMatrixColorFilter(float[] array) {
    if (array.length < 20) {
        throw new ArrayIndexOutOfBoundsException();
    }
    mMatrix.set(array);
    update();
}

重點在 ColorMatrix 這個類。它內部維護一個長度為 20 的陣列 mArray,本質是一個 4×5 的顏色矩陣:

[ a, b, c, d, e,
  f, g, h, i, j,
  k, l, m, n, o,
  p, q, r, s, t ]

第一行決定紅色 R,第二行決定綠色 G,第三行決定藍色 B,第四行決定透明度 A,第五列則是顏色的偏移量。圖片的每個像素的 ARGB 值可以理解為一個 5×1 的分量矩陣 [R, G, B, A, 1],最終結果就是兩個矩陣相乘:

R' = a*R + b*G + c*B + d*A + e;
G' = f*R + g*G + h*B + i*A + j;
B' = k*R + l*G + m*B + n*A + o;
A' = p*R + q*G + r*B + s*A + t;

初始狀態是單位矩陣,對角線為 1,其餘為 0,此時輸出等於輸入,圖片保持原樣:

[ 1 0 0 0 0   - red vector
  0 1 0 0 0   - green vector
  0 0 1 0 0   - blue vector
  0 0 0 1 0 ] - alpha vector
public void reset() {
    final float[] a = mArray;
    Arrays.fill(a, 0);
    a[0] = a[6] = a[12] = a[18] = 1;
}

第五列是偏移量,例如:

[ 1 0 0 0 8
  0 1 0 0 8
  0 0 1 0 8
  0 0 0 1 0 ]

表示每個顏色分量算完之後再加 8。最後一行控制透明度,一般不要動它。

先做個實驗,把綠色通道整列歸零:

public class ColorFilterView extends View {
    private Paint mPaint;
    private Bitmap mBitmap;
    private int padding = 12;

    float[] colorMatrix = {
        1, 0, 0, 0, 0,   // red
        0, 0, 0, 0, 0,   // green
        0, 0, 0, 0, 0,   // blue
        0, 0, 0, 1, 0    // alpha
    };
    private ColorMatrixColorFilter mFilter = new ColorMatrixColorFilter(colorMatrix);

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

    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < 8; i++) {
            mPaint.setColorFilter(mFilter);
            canvas.drawBitmap(mBitmap,
                    (i % 4) * (mBitmap.getWidth() + padding),
                    (i / 4) * (mBitmap.getHeight() + padding), mPaint);
        }
    }
}

把紅綠通道都還原、只留藍色為 0:

float[] colorMatrix = {
    1, 0, 0, 0, 0,   // red
    0, 1, 0, 0, 0,   // green
    0, 0, 0, 0, 0,   // blue
    0, 0, 0, 1, 0    // alpha
};

三個通道全部還原,圖片恢復原樣:

float[] colorMatrix = {
    1, 0, 0, 0, 0,
    0, 1, 0, 0, 0,
    0, 0, 1, 0, 0,
    0, 0, 0, 1, 0
};

再看一個帶縮放與偏移的矩陣:

[ 1 0 0 0 8
  0 2 0 0 8
  0 0 3 0 8
  0 0 0 1 0 ]

含義是紅色分量偏移 8,綠色分量 ×2 後偏移 8,藍色分量 ×3 後偏移 8。

setScale:調整亮度

public void setScale(float rScale, float gScale, float bScale, float aScale) {
    final float[] a = mArray;
    for (int i = 19; i > 0; --i) {
        a[i] = 0;
    }
    a[0] = rScale;
    a[6] = gScale;
    a[12] = bScale;
    a[18] = aScale;
}

結構和 reset() 一樣,只是對角線不是 1,而是傳入的值,用來控制各通道的亮度倍率:

for (int i = 0; i < 24; i++) {
    colorMatrix.setScale(i * .1f, i * .1f, i * .1f, i * .1f);
    matrixColorFilter[i] = new ColorMatrixColorFilter(colorMatrix);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    for (int i = 0; i < 24; i++) {
        mPaint.setColorFilter(matrixColorFilter[i]);
        canvas.drawBitmap(mBitmap,
                (i % 4) * (mBitmap.getWidth() + padding),
                (i / 4) * (mBitmap.getHeight() + padding), mPaint);
    }
}

讓三個通道用不同的倍率,畫面就會偏色:

colorMatrix.setScale(i * .1f, i * .3f, i * .9f, i * .1f);

setRotate:調整色相

/**
 * 繞指定顏色軸旋轉指定角度。
 * axis=0 對應紅色軸,axis=1 對應綠色軸,axis=2 對應藍色軸。
 */
public void setRotate(int axis, float degrees) {
    reset();
    double radians = degrees * Math.PI / 180d;
    float cosine = (float) Math.cos(radians);
    float sine = (float) Math.sin(radians);
    switch (axis) {
        case 0:
            mArray[6] = mArray[12] = cosine;
            mArray[7] = sine;
            mArray[11] = -sine;
            break;
        case 1:
            mArray[0] = mArray[12] = cosine;
            mArray[2] = -sine;
            mArray[10] = sine;
            break;
        case 2:
            mArray[0] = mArray[6] = cosine;
            mArray[1] = sine;
            mArray[5] = -sine;
            break;
        default:
            throw new RuntimeException();
    }
}

從實作不難看出,所謂「色相旋轉」其實是在另外兩個通道構成的平面上做二維旋轉矩陣,用 sin / cos 混合通道值。

for (int i = 0; i < 24; i++) {
    if (i < 8)       colorMatrix.setRotate(0, i * 50);
    else if (i < 16) colorMatrix.setRotate(1, i * 50);
    else             colorMatrix.setRotate(2, i * 50);
    matrixColorFilter[i] = new ColorMatrixColorFilter(colorMatrix);
}

用取模讓每組角度循環,就能看到色相周期性變化的效果:

for (int i = 0; i < 24; i++) {
    if (i < 8)       colorMatrix.setRotate(0, i * 50);
    else if (i < 16) colorMatrix.setRotate(1, (i % 8) * 50);
    else             colorMatrix.setRotate(2, (i % 8) * 50);
    matrixColorFilter[i] = new ColorMatrixColorFilter(colorMatrix);
}

setSaturation:調整飽和度

0 為灰度,1 為正常:

for (int i = 0; i < 24; i++) {
    if (i < 8)       colorMatrix.setSaturation(i * .2f);
    else if (i < 16) colorMatrix.setSaturation(i * .5f);
    else             colorMatrix.setSaturation(i * 2f);
    matrixColorFilter[i] = new ColorMatrixColorFilter(colorMatrix);
}

setConcat / preConcat / postConcat:矩陣複合

public void setConcat(ColorMatrix matA, ColorMatrix matB) {
    float[] tmp;
    if (matA == this || matB == this) {
        tmp = new float[20];
    } else {
        tmp = mArray;
    }
    final float[] a = matA.mArray;
    final float[] b = matB.mArray;
    int index = 0;
    for (int j = 0; j < 20; j += 5) {
        for (int i = 0; i < 4; i++) {
            tmp[index++] = a[j + 0] * b[i + 0] + a[j + 1] * b[i + 5]
                        + a[j + 2] * b[i + 10] + a[j + 3] * b[i + 15];
        }
        tmp[index++] = a[j + 0] * b[4] + a[j + 1] * b[9]
                    + a[j + 2] * b[14] + a[j + 3] * b[19] + a[j + 4];
    }
    if (tmp != mArray) {
        System.arraycopy(tmp, 0, mArray, 0, 20);
    }
}

preConcat() 是前乘,postConcat() 是後乘,兩者最終都調用 setConcat()。由於矩陣乘法不滿足交換律,兩個矩陣的位置對調會得到不同結果,這也是調色效果經常「不對勁」的原因。

二、LightingColorFilter

只有一個構造方法,兩個參數:mul 是顏色乘數,add 是顏色加數。

public LightingColorFilter(int mul, int add) {
    mMul = mul;
    mAdd = add;
    update();
}

計算規則是 R' = R * mulR + addR,各通道同理:

// 保持原樣
mLightingColorFilter[0] = new LightingColorFilter(0xFFFFFFFF, 0x00000000);
// 去掉紅色(紅通道乘 0)
mLightingColorFilter[1] = new LightingColorFilter(0xFF00FFFF, 0x00000000);
// 去掉綠色
mLightingColorFilter[2] = new LightingColorFilter(0xFFFF00FF, 0x00000000);
// 去掉藍色
mLightingColorFilter[3] = new LightingColorFilter(0xFFFFFF00, 0x00000000);
// 增加紅色
mLightingColorFilter[4] = new LightingColorFilter(0xFFFFFFFF, 0x00560000);
// 增加綠色
mLightingColorFilter[5] = new LightingColorFilter(0xFFFFFFFF, 0x00006400);
// 增加藍色
mLightingColorFilter[6] = new LightingColorFilter(0xFFFFFFFF, 0x00000056);

三、PorterDuffColorFilter

同樣只有一個構造方法,接收一個顏色與一個 Porter-Duff 混合模式:

/**
 * 建立一個使用指定顏色與 Porter-Duff 模式的顏色過濾器。
 *
 * @param color 作為來源的 ARGB 顏色
 * @param mode  套用的 Porter-Duff 模式
 */
public PorterDuffColorFilter(@ColorInt int color, @NonNull PorterDuff.Mode mode) {
    mColor = color;
    mMode = mode;
    update();
}

把 18 種混合模式全部跑一遍,就能直觀看到差異:

public class ColorFilterView extends View {
    private Paint mPaint;
    private Bitmap mBitmap;
    private int length = PorterDuff.Mode.values().length;
    private PorterDuffColorFilter[] mFilters = new PorterDuffColorFilter[length];
    private int padding = 12;

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

    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
        int i = 0;
        for (PorterDuff.Mode e : PorterDuff.Mode.values()) {
            mFilters[i++] = new PorterDuffColorFilter(Color.YELLOW, e);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < length; i++) {
            mPaint.setColorFilter(mFilters[i]);
            canvas.drawBitmap(mBitmap,
                    (i % 4) * (mBitmap.getWidth() + padding),
                    (i / 4) * (mBitmap.getHeight() + padding), mPaint);
        }
    }
}

其中 Mode 就是此前 Paint 詳解中介紹過的 18 種混合模式。至此,ColorFilter 的三個子類分析完畢。

實務選型上可以這樣記:需要精細調色(亮度、色相、飽和度、通道偏移)用 ColorMatrixColorFilter;只需要簡單的通道倍增與偏移用 LightingColorFilter,性能更好;需要與已有像素做混合運算(例如給圖片整體染色)用 PorterDuffColorFilter。

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