0

I'm trying to do a game in which i have to rotate a bitmap multiple times.But sometimes it shows Out Of Memory Error.How to solve this? Can anyone suggest me a way to recycle a bitmap or any other way out. This is the code I have written :

       public void rotate() {
         CustomImageView customImageView=this;
        Bitmap bitmap = ((BitmapDrawable)customImageView.getDrawable()).getBitmap();
        Matrix matrix = new Matrix();
        matrix.setRotate(90, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);
        try {
            Bitmap b2 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            if (bitmap != b2) {
                bitmap.recycle();
                bitmap = b2;
            }
        } catch (OutOfMemoryError ex) {
        System.out.println("Exception::out of memory in customimage");
        throw ex;
        }
        customImageView.setImageBitmap(bitmap);
      }
Nadir Belhaj
  • 11,953
  • 2
  • 22
  • 21
jincy abraham
  • 579
  • 2
  • 9
  • 21

1 Answers1

1

OutOfMemoryError is Thrown when the Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

your are reallocating your bitmap for every rotate method call try it this way

Bitmap bitmap = ((BitmapDrawable)customImageView.getDrawable()).getBitmap();
CustomImageView customImageView=this;
Matrix matrix = new Matrix();
public void rotate() {
        matrix.setRotate(90, (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);
        try {
            Bitmap b2 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            if (bitmap != b2) {
                bitmap.recycle();
                bitmap = b2;
            }
        } catch (OutOfMemoryError ex) {
        System.out.println("Exception::out of memory in customimage");
        throw ex;
        }
        customImageView.setImageBitmap(bitmap);
      }

you can also add b2.compress() to compess your bitmap (optional)

Nadir Belhaj
  • 11,953
  • 2
  • 22
  • 21