画布Canvas进阶操作
之前介绍了Canvas画布的基础绘制操作,现在来看看涉及到Canvas自身的还有一些高级操作:旋转、平移、放缩,保存、撤销等操作。熟悉Qt开发的就会觉得非常似曾相识,没错Qt界面开发也有类似API。
1、Canvas变换
对画布进行旋转、平移、放缩等操作,会对绘制产生影响。
1.1、缩放
①scale(float sx, float sy):将画布的x、y轴都压缩为原来的sx、sy倍。放缩后的坐标原点和压缩前的坐标原点在同一个地方,都是画布的左上角。
/**
* Preconcat the current matrix with the specified scale.
*
* @param sx The amount to scale in X
* @param sy The amount to scale in Y
*/
public void scale(float sx, float sy) {
if (sx == 1.0f && sy == 1.0f) return;
nScale(mNativeCanvasWrapper, sx, sy);
}②scale(float sx, float sy, float px, float py):以自定义点(px,py)为中心缩放画布
/**
* Preconcat the current matrix with the specified scale.
*
* @param sx The amount to scale in X
* @param sy The amount to scale in Y
* @param px The x-coord for the pivot point (unchanged by the scale)
* @param py The y-coord for the pivot point (unchanged by the scale)
*/
public final void scale(float sx, float sy, float px, float py) {
if (sx == 1.0f && sy == 1.0f) return;
translate(px, py);
scale(sx, sy);
translate(-px, -py);
}1.2、平移
①translate(float dx, float dy):画布的位置并没有变,只是移动了坐标系
/**
* Preconcat the current matrix with the specified translation
*
* @param dx X转换距离
* @param dy Y转换距离
*/
public void translate(float dx, float dy) {
if (dx == 0.0f && dy == 0.0f) return;
nTranslate(mNativeCanvasWrapper, dx, dy);
}4.3、旋转
①rotate(float degrees):以原点为中心旋转指定角度
②rotate(float degrees, float px, float py):以自定义点(px,py)为中心旋转画布
/**
* Preconcat the current matrix with the specified rotation.
*
* @param degrees The amount to rotate, in degrees
* @param px The x-coord for the pivot point (unchanged by the rotation)
* @param py The y-coord for the pivot point (unchanged by the rotation)
*/
public final void rotate(float degrees, float px, float py) {
if (degrees == 0.0f) return;
translate(px, py);
rotate(degrees);
translate(-px, -py);
}4.4、倾斜
①skew(float sx, float sy):画布倾斜操作。x,y方向倾斜的角度的tan值
/**
* Preconcat the current matrix with the specified skew.
*
* @param sx The amount to skew in X
* @param sy The amount to skew in Y
*/
public void skew(float sx, float sy) {
if (sx == 0.0f && sy == 0.0f) return;
nSkew(mNativeCanvasWrapper, sx, sy);
}2、Canvas裁剪
裁剪clip后,画布只在裁剪区域内绘制有效。此外还有反向裁剪clipOut,画布只在裁剪范围外有效。
2.1、clip
①clipPath(Path path)
②clipPath(Path path,Region.Op op)
③clipRect(RectF rect)
④clipRect(Rect rect)
⑤clipRect(float left, float top, float right, float bottom)
⑥clipRect(int left, int top, int right, int bottom)
2.2、clipOut
①clipOutPath(Path path)
②clipOutRect(RectF rect)
③clipOutRect(Rect rect)
④clipOutRect(float left, float top, float right, float bottom)
⑤clipOutRect(int left, int top, int right, int bottom)
3、Canvas快照
在画布上进行一系列操作,可以对选定的画布状态进行保存,或者不想要绘制某个元素,执行撤销操作。
3.1、保存
①save():保存canvas的状态
②saveLayer(RectF bounds,Paint paint):创建新的图层,之后的绘制都会在这个图层之上绘制,直到调用restore()
③saveLayer(float left, float top, float right, float bottom,Paint paint)
④getSaveCount():返回Canvas私有堆栈上矩阵/剪辑状态的数量,这等于save() - restore()调用次数。
3.2、恢复
①restore():恢复到最近上一个画布状态
②restoreToCount(int saveCount):恢复到指定的第saveCount个保存位置
相关资料:

