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

Android 變形處理(Transform)之 Matrix 用法全解

編輯:關於 Android 程式設計

Android 的視覺變形大致分成兩塊:2D 的縮放、扭曲、平移、旋轉靠 Matrix 完成;3D 的透視變形則交給 Camera。本文先把 Matrix 這塊地基打穩,理解它之後再看 Camera 會順很多。

效果預覽

原圖:

變形後:

Matrix 是什麼

它是一個 3×3 的座標變換矩陣,用來對圖形做座標轉換。

圖 1.1 中,A 是座標矩陣,C 是原始座標矩陣,R 是兩者相乘的結果。由此可以推出:

x' = a*x + b*y + c
y' = d*x + e*y + f

最後一列比較少資料提到,不過初始值 g = h = 0,i 則是縮放比例、初始值為 1。實務上幾乎不會去改這一排。

初始化的單位矩陣是 {1, 0, 0, 0, 1, 0, 0, 0, 1}。

矩陣各位置代表什麼

如果 A = {1, 0, 100, 0, 1, -100, 0, 0, 2},代入公式可以算出:

x' = x + 100
y' = y - 100

也就是在原圖基礎上右移 100、上移 100,單位是像素。而第三列第三行為 2,表示縮放比例是「原來的 1/2」——這裡是分母,容易搞反,得多留意。

整理成對照表:

| scaleX,  skewX,  translateX |
| skewY,   scaleY, translateY |
| 0,       0,      scale      |

實作:用 setValues 直接塞矩陣

public class MatrixTransformView extends View {

    private Matrix mMatrix;
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Bitmap mBitmap;

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

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

    public void setDrawable(int resId) {
        mBitmap = BitmapFactory.decodeResource(getContext().getResources(), resId);
    }

    /*
     * 設置矩陣,並重繪
     */
    public void setMatrixValues(float[] array) {
        if (mMatrix == null) {
            mMatrix = new Matrix();
        }
        mMatrix.reset();
        mMatrix.setValues(array);
        invalidate();
    }

    public void resetMatrix() {
        if (mMatrix != null) {
            mMatrix.reset();
        }
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mMatrix != null) {
            Paint paint = mPaint;
            canvas.drawBitmap(mBitmap, mMatrix, paint);
        }
        super.onDraw(canvas);
    }
}

透過 setValues() 把 3×3 的九個數值一次設定好即可。要特別注意的是,呼叫 setMatrixValues 之後必須呼叫 invalidate(),View 才會重新觸發 onDraw 把新效果畫出來,否則畫面不會有任何變化。

用 Matrix 的語意化方法

直接算矩陣座標固然可行,但要處理旋轉就得搬三角函數出來的,實務上很麻煩。因此 Matrix 類別包裝了一組更好用的方法,分成三種風格:

  • set 系列:setScale、setSkew、setTranslate、setRotate
  • post 系列:postScale、postSkew、postTranslate、postRotate
  • pre 系列:preScale、preSkew、preTranslate、preRotate

簡單記憶:set 是直接設定,每次呼叫都會先重置矩陣;post 是後乘,效果會與既有變形累加;pre 是右乘,在 2D 场景下可以先粗略理解成與 post 類似,等到研究 3D 變形時再細究差異。

實作:用語意化方法

public class MatrixTransformView extends View {

    private Matrix mMatrix;
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Bitmap mBitmap;

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

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

    public void setDrawable(int resId) {
        mBitmap = BitmapFactory.decodeResource(getContext().getResources(), resId);
    }

    /*
     * 設置矩陣,並重繪
     */
    public void setMatrixValues(float[] array) {
        if (mMatrix == null) {
            mMatrix = new Matrix();
        }
        mMatrix.reset();
        mMatrix.setValues(array);
        invalidate();
    }

    public void postMatrixScale(float scaleX, float scaleY, float centerX, float centerY) {
        if (mMatrix == null) {
            mMatrix = new Matrix();
        }
        mMatrix.postScale(scaleX, scaleY, centerX, centerY);
        invalidate();
    }

    public void postMatrixSkew(float skewX, float skewY, float centerX, float centerY) {
        if (mMatrix == null) {
            mMatrix = new Matrix();
        }
        mMatrix.postSkew(skewX, skewY, centerX, centerY);
        invalidate();
    }

    public void postMatrixTranslate(float translateX, float translateY) {
        if (mMatrix == null) {
            mMatrix = new Matrix();
        }
        mMatrix.postTranslate(translateX, translateY);
        invalidate();
    }

    public void postMatrixRotate(float degree, float centerX, float centerY) {
        if (mMatrix == null) {
            mMatrix = new Matrix();
        }
        mMatrix.postRotate(degree, centerX, centerY);
        invalidate();
    }

    public void resetMatrix() {
        if (mMatrix != null) {
            mMatrix.reset();
        }
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mMatrix != null) {
            Paint paint = mPaint;
            canvas.drawBitmap(mBitmap, mMatrix, paint);
        }
        super.onDraw(canvas);
    }
}

擴展:怎麼變形一個 ViewGroup

因為變形需要 Canvas 繪製、而 Canvas 繪製需要 Bitmap,所以上面做法是自訂一個 View 並以 setDrawable 傳入 Bitmap——這也意味著變形對象必須是 Bitmap。

那如果想變形的是整個 ViewGroup(例如一個包含多個子元件的卡片)呢?思路是先把 ViewGroup 畫成一張 Bitmap,再對這張 Bitmap 變形:

Matrix m = new Matrix();
m.setValues(new float[] {
    1, 0, 0,
    0, 1, 0,
    0, 0, 1
});
Bitmap bp = Bitmap.createBitmap(viewGroup.getWidth(), viewGroup.getHeight(), Bitmap.Config.RGB_565);
Canvas can = new Canvas(bp);
viewGroup.draw(can);
bp = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), m, true);
img.setImageBitmap(bp);

做法是把 ViewGroup 轉成 Bitmap,再用自訂的 ImageView 呈現變形後的結果,最後把原本的 ViewGroup 隱藏起來,視覺上就達到「整個容器在變形」的效果。

兩個值得繼續追的問題

第一,pre 與 post 的精確差異為何?簡短答案是矩陣乘法順序不同(pre 右乘、post 左乘),當變形只有一層時看不出差別,一旦叠加多層就會明顯分歧。

第二,能否直接對 ViewGroup 做變形而不必先轉成 Bitmap?答案是可行的——自訂 ViewGroup 並覆寫 dispatchDraw,在 canvas.save() 後套用 Matrix、drawChild 繪製子元件,最後 canvas.restore()。這樣做的好處是保留視圖階層與事件處理能力,缺點則是效能與複雜度都會上升。若只是靜態展示,轉 Bitmap 反而更省事。

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