Android: How to get a custom view to redraw partially?

前端 未结 2 791
梦谈多话
梦谈多话 2020-12-02 19:28

I have a custom view that fills my entire screen. (A piano keyboard) When a user touches the key, it causes invalidate() to be called and the whole keyboard get

2条回答
  •  失恋的感觉
    2020-12-02 19:56

    Current nice workaround is to manually cache the full canvas to a bitmap:

     private void onDraw(Canvas canvas)
     {
         if (!initialDrawingIsPerformed)
         {
              this.cachedBitmap = Bitmap.createBitmap(getWidth(), getHeight(),
                Config.ARGB_8888); //Change to lower bitmap config if possible.
              Canvas cacheCanvas = new Canvas(this.cachedBitmap);
              doInitialDrawing(cacheCanvas);
              canvas.drawBitmap(this.cachedBitmap, 0, 0, new Paint());
              initialDrawingIsPerformed = true;
         }
         else
         {
              canvas.drawBitmap(this.cachedBitmap, 0, 0, new Paint());
              doPartialRedraws(canvas);
         }
     }
    

    Ofcourse, you need to store the info about what to redraw yourself and preferably not use a new Paint everytime, but that are details.

    Also note: Bitmaps are quite heavy on the memory usage of your app. I had crashes when I cached a View that was used with a scroller and that was like 5 times the height of the device, since it used > 10MB memory!

提交回复
热议问题