1. Canvas 裁剪类方法
1.1 裁剪矩形
// left, top, right, bottom 矩形的边界
clipRect(int left, int top, int right, int bottom)
复制代码
注:加上 Canvas.save() 和 Canvas.restore() 来及时恢复绘制范围。
1.2 裁剪自定义的 Path 图形
// path 图形
clipPath(Path path)
复制代码
裁剪的保留可以通过 path.setFillType() 设置。
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)
复制代码
例:
canvas.save();
canvas.skew(0, 0.5f);
canvas.drawBitmap(bitmap, x, y, paint);
canvas.restore();
复制代码
3. 通过 Matrix 做常见变换
3.1 常见的变换(平移、旋转、缩放、错切)
步骤:
- 创建 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)
复制代码
例:
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 移动到投影中心
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);
复制代码
先学会绘制各种静态的图片,在将这些静态的图片一张一张的连贯上,就变成了动画。