Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I debug drawing on Canvas in onDraw method?

Tags:

android

I'm implementing my custom View where I override onDraw() method in order to draw some set of objects.

The objects are supposed to be placed in a coordinates which are evaluated in a particular way. The code placing those objects works incorrectly (some of them are either not drawn at all or are overlayed by other objects) so that I need to do some debugging to execute it line-by-line and watch what is actually being drawn step-by-step.

However as far as I understand the actual picture is shown on the screen after all the drawing is completed since when I'm executing canvas.drawBitmap line nothing is appearing on my emulator's screen.

My question is: What is the best (or maybe the only) way to debug onDraw() code? I did some research in Adroid dev portal and here in posted questions but was unable to find the solution.

like image 950
Alexey R. Avatar asked Oct 21 '25 04:10

Alexey R.


1 Answers

Haven't tried this, but it should put you on the right track:

  • At the start of your onDraw method, make a new Bitmap using the width and height from the canvas
  • Make a new Canvas from the Bitmap
  • Run your draw calls on this Canvas
  • You can inspect the Bitmap from the Android Studio debugger, and will update with every draw call
  • If you also want to draw the data to the screen, you can use drawBitmap on the original Canvas with your full Bitmap, but this shouldn't be needed for debugging

Don't leave this in production code

@Override
public void onDraw(Canvas canvas) {
    Bitmap screenBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas screenCanvas = new Canvas(screenBitmap);

   /* Run draw calls on screenCanvas, inspect screenBitmap for result*/
}
like image 200
Robert Williams Avatar answered Oct 23 '25 20:10

Robert Williams