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

前端 未结 2 787
梦谈多话
梦谈多话 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!

    0 讨论(0)
  • 2020-12-02 20:01

    To complement Peterdk's answer, you could save your operations in a Picture instead of a Bitmap.

    • A Bitmap will save all pixels, like he said it could take a lot of memory.
    • A Picture will save the calls, like drawRect, drawLine, etc.

    It depends of what is really heavy in your application : a lot of draw operations, a few draw operations but controlled by heavy calculations, a lot of blank/unused space (prefer Picture) etc...

    0 讨论(0)
提交回复
热议问题