Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear Bitmap in Android

I create first chart using bitmap and canvas. How I can clear bitmap for drawing new chart?

ImageView imageView = new ImageView(this);
Bitmap bitmap = Bitmap.CreateBitmap(w, h, Bitmap.Config.Argb8888);
Canvas canvas = new Canvas(bitmap);
...
imageView.SetImageBitmap(bitmap);
relativeLayout.AddView(imageView);
like image 324
Kirill Avatar asked May 27 '15 14:05

Kirill


3 Answers

You can use eraseColor on bitmap to set its color to Transparent. It will useable again without recreating it.

bitmap.eraseColor(Color.TRANSPARENT);

Further reading here

like image 177
Jibran Khan Avatar answered Nov 22 '22 14:11

Jibran Khan


ImageView imageView = new ImageView(this);
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
    // Your Other code
imageView.setImageBitmap(bitmap);
relativeLayout.AddView(imageView);

Now release memory of bitmap by below code

bitmap.recycle();

Help of recycle() method of bitmap as per this.

public void recycle () Added in API level 1 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. The bitmap is marked as "dead", meaning it will throw an exception if getPixels() or setPixels() is called, and will draw nothing. This operation cannot be reversed, so it should only be called if you are sure there are no further uses for the bitmap. 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.

like image 24
Hiren Patel Avatar answered Nov 22 '22 13:11

Hiren Patel


The solution was to use

bitmap.eraseColor
like image 38
Kirill Avatar answered Nov 22 '22 14:11

Kirill