问题描述
我正在尝试绘制动画.为此,我扩展了 View 并覆盖了 onDraw() 方法.我所期望的是,每次调用 onDraw() 时,画布都会处于我离开它的状态,我可以选择清除它或只绘制它的一部分(这就是我使用 SurfaceView 时的工作方式) 但每次画布回来时都已经清除了.有什么办法可以不清除吗?或者也许可以将之前的状态保存到位图中,这样我就可以绘制该位图,然后在其上方绘制?
I am trying to draw an animation. To do so I have extended View and overridden the onDraw() method. What I would expect is that each time onDraw() is called the canvas would be in the state that I left it in and I could choose to clear it or just draw over parts of it (This is how it worked when I used a SurfaceView) but each time the canvas comes back already cleared. Is there a way that I can not have it cleared? Or maybe save the previous state into a Bitmap so I can just draw that Bitmap and then draw over top of it?
推荐答案
我不确定是否有办法.但是对于我的自定义视图,我要么在每次调用 onDraw() 时重新绘制所有内容,要么绘制到位图,然后将位图绘制到画布(如您在问题中所建议的那样).
I'm not sure if there is a way or not. But for my custom views I either redraw everything each time onDraw() is called, or draw to a bitmap and then draw the bitmap to the canvas (like you suggested in your question).
这是我的做法
class A extends View {
private Canvas canvas;
private Bitmap bitmap;
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (bitmap != null) {
bitmap .recycle();
}
canvas= new Canvas();
bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canvas.setBitmap(bitmap);
}
public void destroy() {
if (bitmap != null) {
bitmap.recycle();
}
}
public void onDraw(Canvas c) {
//draw onto the canvas if needed (maybe only the parts of animation that changed)
canvas.drawRect(0,0,10,10,paint);
//draw the bitmap to the real canvas c
c.drawBitmap(bitmap,
new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()),
new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()), null);
}
}
这篇关于Android View.onDraw() 总是有一个干净的 Canvas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!