总是有一个干净的画布

总是有一个干净的画布

本文介绍了安卓View.onDraw()总是有一个干净的画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制动画。要做到这一点我已经扩展视图,并覆盖了的OnDraw()方法。我会想到的是,每一次的OnDraw()被调用画布会在我离开时的状态,我可以选择清除它,还是画在它的一部分(这是它是如何工作的时候我用了一个SurfaceView ),但每个画布回来时已经被清除。有没有办法,我不能有它清除?或者,也许节省previous状态转变成位图,所以我可以只画了位图,然后绘制在它的上面?

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).

下面是我如何做到这一点

Here is how i do it

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);
    }
}

这篇关于安卓View.onDraw()总是有一个干净的画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:30