版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zqd1984309864/article/details/78337893
遇到这两个防法正好记录一下,有一个简单的例子,画一个钟表的刻度盘,首先画圆,然后通过旋转画布画刻度,下面主要代码:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/**
* 画圆
*/
canvas.drawCircle(mWidth / 2, mHeight / 2, mWidth / 2, mPaint);
/**
* 画12点位置
*/
canvas.drawLine(mWidth / 2, mHeight / 2 - mWidth / 2, mWidth / 2, mHeight / 2 - mWidth / 2 + 50, mPaint);
/**
* 画中心点
*/
canvas.drawPoint(mWidth / 2, mHeight / 2, mPaint);
/**
* 旋转画布画画其他位置的刻度
*/
for (int i = 0; i < 11; i++) {
canvas.rotate(30, mWidth / 2, mHeight / 2);
canvas.drawLine(mWidth / 2, mHeight / 2 - mWidth / 2, mWidth / 2, mHeight / 2 - mWidth / 2 + 50, mPaint);
}
}
效果图:
那么现在修改代码添加两个放法save,和restore如下代码所示:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/**
* 画圆
*/
canvas.drawCircle(mWidth / 2, mHeight / 2, mWidth / 2, mPaint);
/**
* 画12点位置
*/
canvas.drawLine(mWidth / 2, mHeight / 2 - mWidth / 2, mWidth / 2, mHeight / 2 - mWidth / 2 + 50, mPaint);
/**
* 画中心点
*/
canvas.drawPoint(mWidth / 2, mHeight / 2, mPaint);
/**
* 旋转画布画画其他位置的刻度
*/
for (int i = 0; i < 11; i++) {
canvas.save();
canvas.rotate(30, mWidth / 2, mHeight / 2);
canvas.restore();
canvas.drawLine(mWidth / 2, mHeight / 2 - mWidth / 2, mWidth / 2, mHeight / 2 - mWidth / 2 + 50, mPaint);
}
}
效果图如下:
总结:好了我们看到了所有的刻度都画在12点了,为什么,在一般情况下save放法和restore一般是成对调用的,save放法用于保存当前画布状态,而restore放法则是回复之前保存的画布的状态,在本例中,我再旋转画布之前进行保存画布状态,(此时保存的画布状态是没有经过旋转的),我在旋转之后调用restore恢复之前保存的状态,所以目前的画布状态仍然是没有旋转过的,所以所有的刻度都画在12点位置,不知道明白了没有,在save和restore一般进行画布的旋转缩放平移等操作,最后再用箭头表示一下画布的状态。