經常使用定義 View 方法彙總 Canvas 裁剪、幾何變換(四)

1. Canvas 裁剪類方法

1.1 裁剪矩形

// left, top, right, bottom 矩形的邊界
clipRect(int left, int top, int right, int bottom)
複製代碼

注:加上 Canvas.save()Canvas.restore() 來及時恢復繪製範圍。canvas

1.2 裁剪自定義的 Path 圖形

// path 圖形
clipPath(Path path)
複製代碼

裁剪的保留能夠經過 path.setFillType() 設置。bash

2. Canvas 的常見二維變換

2.1 平移變換

// dx 和 dy 表示橫向和縱向的位移。
translate(float dx, float dy);
複製代碼

2.2 旋轉變換

// degrees 旋轉角度,單位是度,方向是順時針爲正向; 
// px 和 py 是軸心的位置
rotate(float degrees, float px, float py) 
複製代碼

2.3 縮放變換

// sx sy 是橫向和縱向的放縮倍數; 
// px py 是放縮的軸心。
scale(float sx, float sy, float px, float py);
複製代碼

2.4 錯切變換

// sx 和 sy 是 x 方向和 y 方向的錯切係數。
skew(float sx, float sy)
複製代碼

例:app

canvas.save();
canvas.skew(0, 0.5f);
canvas.drawBitmap(bitmap, x, y, paint);
canvas.restore();
複製代碼

3. 經過 Matrix 作常見變換

3.1 常見的變換(平移、旋轉、縮放、錯切)

步驟:post

  • 建立 Matrix 對象;
  • 使用 pre/postTranslate/Rotate/Scale/Skew() 方法來設置幾何變換;
  • 使用 Canvas.setMatrix(matrix) 或 Canvas.concat(matrix) 來把幾何變換應用到 Canvas。
Matrix matrix = new Matrix();
...
matrix.reset();
matrix.postTranslate();
matrix.postRotate();
canvas.save();
canvas.concat(matrix);
canvas.drawBitmap(bitmap, x, y, paint);
canvas.restore();
複製代碼

3.2 自定義變換

用點對點映射的方式設置變換動畫

// src 和 dst 是源點集合目標點集;
// srcIndex 和 dstIndex 是第一個點的偏移;
// pointCount 是採集的點的個數(個數不能大於 4,由於大於 4 個點就沒法計算變換了)
setPolyToPoly(float[] src, int srcIndex, float[] dst, int dstIndex, int pointCount)
複製代碼

例:ui

Matrix matrix = new Matrix();
float pointsSrc = {left, top, right, top, left, bottom, right, bottom};
float pointsDst = {left - 10, top + 50, right + 120, top - 90, left + 20, bottom + 30, right + 20, bottom + 60};
...
matrix.reset();
matrix.setPolyToPoly(pointsSrc, 0, pointsDst, 0, 4);
canvas.save();
canvas.concat(matrix);
canvas.drawBitmap(bitmap, x, y, paint);
canvas.restore();
複製代碼

4. Camera 三維變換

4.1 旋轉變換

rotateX(deg);
rotateY(deg);
rotateZ(deg);
rotate(x, y, z);
複製代碼

注:旋轉時須要將 canvas 移動到投影中心spa

canvas.save();
camera.save(); // 保存 Camera 的狀態
canvas.translate(centerX, centerY); // 旋轉以後把投影移動回來
camera.rotateX(30); // 旋轉 Camera 的三維空間
camera.applyToCanvas(canvas); // 把旋轉投影到 Canvas
canvas.translate(-centerX, -centerY); // 旋轉以前把繪製內容移動到軸心(原點)
camera.restore(); // 恢復 Camera 的狀態
canvas.drawBitmap(bitmap, point1.x, point1.y, paint);
canvas.restore();
複製代碼
camera.save();
matrix.reset();
camera.rotateY(30);
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-center2X, -center2Y);
matrix.postTranslate(center2X, center2Y);
canvas.save();
canvas.concat(matrix);
canvas.drawBitmap(bitmap, point2.x, point2.y, paint);
canvas.restore();
複製代碼

4.2 移動

translate(float x, float y, float z);
複製代碼

4.3 設置虛擬相機的位置

// 單位是 英寸(inch)。
// 1 英寸 = 72 像素
setLocation(x, y, z);
複製代碼

先學會繪製各類靜態的圖片,在將這些靜態的圖片一張一張的連貫上,就變成了動畫。rest

參考:HenCoder Android 開發進階:自定義 View 1-4 Canvas 對繪製的輔助code

相關文章
相關標籤/搜索