3

I am making a drawing app, in which user can draw some basic shapes like square, triangle, line and free hand drawing.

I have created a custom view on which user can draw anything. When user select any shape, I am making new instance of custom view. And adding that view into root layout view.

After adding few shapes, app getting crash. As per the my observation, onSizeChanged() method making bitmap of device width and height. It might be a big bitmap if I am working on high resolution devices.

Quesion 1: Is it required to generate bitmap each time to draw on canvas?

Question 2: How to avoid and take care of out of memory issue?

`

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) 
{
super.onSizeChanged(w, h, oldw, oldh);
canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
drawCanvas = new Canvas(canvasBitmap);
}

`

I have seen in many drawing example, they are making instance of bitmap and drawing it on canvas. Why is it required?

https://code.tutsplus.com/tutorials/android-sdk-create-a-drawing-app-touch-interaction--mobile-19202

Rohan Patel
  • 1,758
  • 2
  • 21
  • 38

2 Answers2

0

Hi try to call recycle() method on bitmap after you done drawing , this helped me a lot , Using recycle() method,

Free the native object associated with this bitmap, and clear the reference to the pixel data. This will not free the pixel data synchronously; it simply allows it to be garbage collected if there are no other references..

Please consider reading this official documentaion here.

Omar Dhanish
  • 885
  • 7
  • 18
  • The recycler method is not recommended to be called. This is an advanced call, and normally need * not be called, since the normal GC process will free up this memory when * there are no more references to this bitmap. – Edhar Khimich Mar 01 '21 at 16:30
0

Quesion 1: Is it required to generate bitmap each time to draw on canvas?

If you don't need care about the bitmap and only want to show the drawing to the user, then there is no need to generate bitmap each time. Your custom view already has a canvas and an underlying bitmap attached to it. You can simple draw to that bitmap using the canvas via View.onDraw(Canvas canvas)

Question 2: How to avoid and take care of out of memory issue?

As you add more and more bitmaps, the system keeps allocating memory and at a certain point would throw OutOfMemoryError. The following are ways to avoid this:

  1. Avoid creating new bitmaps and draw directly to the view's canvas via View.onDraw(Canvas canvas)
  2. Don't let the users create too many bitmaps. Limit them based on the memory allocation
  3. Try to re use the existing bitmap if it's possible
  4. Create bitmap with size that you require and not more
  5. If color is not your major concern don't use Bitmap.Config.ARGB_8888 but rather try other Config options
Henry
  • 17,490
  • 7
  • 63
  • 98