Android中使用自定义View的几个两个注意点
记录一下使用自定义View需要注意的两个知识点:
1、在onDraw方法中尽量不要new对象。
特别是一些需要不断调用onDraw方法来实现的动态效果,就像我以前文章的那个自定义圆环进度条的实现时,一直不断的调用onDraw方法来实现动态的效果,如果一直在里面new对象,会导致内存溢出。这个是特别要注意的点。
2、canvas.save();和canvas.restore();的使用
save:用来保存Canvas的状态。save之后,可以调用Canvas的平移、放缩、旋转、错切、裁剪等操作。
restore:用来恢复Canvas之前保存的状态。防止save后对Canvas执行的操作对后续的绘制有影响。
save和restore要配对使用(restore可以比save少,但不能多),如果restore调用次数比save多,会引发Error。
可以通过SDK中的注释来辅助理解:
/** * Saves the current matrix and clip onto a private stack. Subsequent * calls to translate,scale,rotate,skew,concat or clipRect,clipPath * will all operate as usual, but when the balancing call to restore() * is made, those calls will be forgotten, and the settings that existed * before the save() will be reinstated. * * @return The value to pass to restoreToCount() to balance this save() */ public native int save();
/** * This call balances a previous call to save(), and is used to remove all * modifications to the matrix/clip state since the last save call. It is * an error to call restore() more times than save() was called. */ public native void restore();
例如:我们先想在画布上绘制一个右向的三角箭头,当然,我们可以直接绘制,这里,我们先把画布旋转90°,画一个向上的箭头,然后再旋转回来(这种旋转操作对于画圆周上的标记非常有用)。然后,我们想在右下角有个20像素的圆,那么,onDraw中的核心代码是:
nt px = getMeasuredWidth(); int py = getMeasuredWidth(); // Draw background canvas.drawRect(0, 0, px, py, backgroundPaint); canvas.save(); canvas.rotate(90, px/2, py/2); // Draw up arrow canvas.drawLine(px / 2, 0, 0, py / 2, linePaint); canvas.drawLine(px / 2, 0, px, py / 2, linePaint); canvas.drawLine(px / 2, 0, px / 2, py, linePaint); canvas.restore(); // Draw circle canvas.drawCircle(px - 10, py - 10, 10, linePaint);
运行后的效果如下:
如果我们不调用save和restore:
效果如下:
不进行Canvas的save和restore操作的话,所有的图像都是在画布旋转90°后的画布上绘制的。当执行完onDraw方法,系统自动将画布恢复回来。save和restore操作执行的时机不同,就能造成绘制的图形不同。
所以,save和restore之间,往往夹杂的是对Canvas的特殊操作。