【问题标题】:Memory Error While Rotating An Image旋转图像时出现内存错误
【发布时间】:2014-11-08 03:11:18
【问题描述】:

我正在尝试做一个游戏,我必须多次旋转位图。但有时它会显示内存不足错误。如何解决这个问题?谁能建议我一种回收位图或任何其他方式的方法。这是我写的代码:

       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);
      }

【问题讨论】:

  • 可能是您旋转的图像太大。首先,缩小图像然后旋转它。
  • @Hamid Shatu : 非常感谢 :) 缩放完成了这项工作

标签: android out-of-memory bitmapimage recycle


【解决方案1】:

当虚拟机无法运行时抛出 OutOfMemoryError 分配一个对象,因为它内存不足,并且没有更多内存 可以由垃圾收集器提供。

您正在为每个旋转方法调用重新分配位图尝试这种方式

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);
      }

你也可以添加 b2.compress() 来压缩你的位图(可选)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 2011-12-19
    • 2018-06-29
    • 1970-01-01
    相关资源
    最近更新 更多