- save:保存画布的状态
- restore:将画布保存到之前保存的状态
这有什么用呢? 当调用 save 保存了画布的状态之后,就可以对画布为所欲为了(调用 Canvas 的平移、放缩、旋转、错切、裁剪等操作),反正可以调用 restore 恢复状态不是吗?
save 和 restore 一般配套使用。
一个例子:
class CustomView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
private val paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val bitmap: Bitmap by lazy {
BitmapFactory.decodeResource(
resources,
R.drawable.ic_launcher
)
}
init {
paint.color = Color.GREEN
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.save()
val path = Path()
path.addCircle(bitmap.width / 2.0f, bitmap.height/ 2.0f, 35.0f, Path.Direction.CW)
canvas.clipPath(path)
val matrix = Matrix()
canvas.drawBitmap(bitmap, matrix, paint)
canvas.restore()
canvas.save()
canvas.translate(100.0f, 100.0f)
canvas.rotate(45.0f)
canvas.drawBitmap(bitmap, matrix, paint)
canvas.restore()
}
效果图:
多次保存和恢复
save 方法可以保存多次,restore 方法也可以恢复多次。 可以理解为 save 一次,就会将状态信息压入栈中;restore 一次,就会将栈顶元素取出栈。
通过例子来理解:
class CustomView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
private val paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val borderPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val textPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
init {
paint.color = Color.BLUE
borderPaint.color = Color.RED
borderPaint.style = Paint.Style.STROKE
borderPaint.strokeWidth = 1f
textPaint.color = Color.RED
textPaint.textSize = 30f
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawText("1", 110f, 30f, textPaint)
canvas.drawRect(0f, 0f, 100f, 100f, borderPaint)
canvas.drawRect(0f, 0f, 50f, 50f, paint)
canvas.save()
canvas.translate(100f, 100f)
canvas.drawText("2", 110f, 30f, textPaint)
canvas.drawRect(0f, 0f, 100f, 100f, borderPaint)
canvas.drawRect(0f, 0f, 50f, 50f, paint)
canvas.save()
canvas.translate(100f, 100f)
canvas.drawText("3", 110f, 30f, textPaint)
canvas.drawRect(0f, 0f, 100f, 100f, borderPaint)
canvas.drawRect(0f, 0f, 50f, 50f, paint)
canvas.save()
canvas.translate(100f, 100f)
canvas.drawText("4", 110f, 30f, textPaint)
canvas.drawRect(0f, 0f, 100f, 100f, borderPaint)
canvas.drawRect(0f, 0f, 50f, 50f, paint)
}
}
例子中 save 了三次状态,每次 save 完之后,会将画布下移和右移 100 px。运行效果如下:
这时候,栈中有编号为 1,2,3 的三个状态。 下面我们依次恢复状态。
restore 一次,popup 出栈顶的编号为 3 的状态,所以绘制的绿色正方形在 3 的区域。
paint.color = Color.GREEN
canvas.restore()
canvas.drawRect(50f, 50f, 100f, 100f, paint)
再 restore 一次,popup 出栈顶的编号为 2 的状态,所以绘制的绿色正方形在 2 的区域。
canvas.restore()
canvas.drawRect(50f, 50f, 100f, 100f, paint)
再 restore 一次,popup 出栈顶的编号为 1 的状态,所以绘制的绿色正方形在 1 的区域。这时栈就空了。
canvas.restore()
canvas.drawRect(50f, 50f, 100f, 100f, paint)
上面分三次依次恢复到原始状态 1。
如果想恢复到指定状态也是可以的,可以用 restoreToCount 方法,参数就是想恢复到的状态的编号。 如果指定的状态不在栈顶,会清空掉指定状态上面的所有元素。
下面演示直接恢复到原始状态
paint.color = Color.GREEN
canvas.restoreToCount(1)
canvas.drawRect(50f, 50f, 100f, 100f, paint)
|