Android View.onDraw() always has a clean Canvas

后端 未结 3 1412
误落风尘
误落风尘 2020-12-01 08:15

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 wou

3条回答
  •  一个人的身影
    2020-12-01 09:05

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

提交回复
热议问题