【问题标题】:how to avoid OUtOfMemory problems with create Bitmap如何避免创建位图的 OUTOfMemory 问题
【发布时间】:2014-11-25 16:41:37
【问题描述】:

我正在尝试使用此代码从视图创建位图:

public Bitmap getmyBitmap(View v)
{
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
        Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);
        return b;
}

但我有一个内存不足的问题。我可以通过将此选项添加到不推荐的清单文件 android:largeHeap="true" 来修复它!

我正在考虑回收视图,可以解决吗?

这是打印堆栈:

11-25 15:31:46.556 2115-2115/com.myproject.android E/dalvikvm-heap: 4096016 字节分配内存不足。 11-25 15:31:46.616
2115-2115/com.myproject.android E/dalvikvm-heap:内存不足 4096016 字节分配。 11-25 15:31:46.666
2115-2115/com.myproject.android E/dalvikvm-heap:内存不足 4096016 字节分配。 11-25 15:31:54.016
2115-2115/com.myproject.android E/dalvikvm-heap:内存不足 1879696 字节分配。 11-25 15:31:54.016
2115-2115/com.myproject.android E/AndroidRuntime:致命异常: 主要的

【问题讨论】:

    标签: android view bitmap out-of-memory android-canvas


    【解决方案1】:

    我认为你得到了很多位图,这会使你的系统内存过载,或者如果它是一个单独的,则认为它是一个非常巨大的,所以,要解决这个问题,你必须做两件事,首先 确保您不要为同一个 Bitmap 多次运行此方法(因为这会导致大量位图存储在您的内存中,并且所有这些位图都属于同一个),第二使用自定义方法来缩放您的位图,以降低它的大小,从而降低它的内存占用区域:

    // to scale your Bitmaps
    // assign newWidth and newHeight with the corresponding width and height that doesn't make your memory overloads and in the same time doesn't make your image loses it's Features
    public static Bitmap scaleBitmap(Bitmap bitmapToScale, float newWidth, float newHeight) {
    
        if(bitmapToScale == null)
            return null;
        //get the original width and height
        int width = bitmapToScale.getWidth();
        int height = bitmapToScale.getHeight();
        // create a matrix for the manipulation
        Matrix matrix = new Matrix();
    
        // resize the bit map
        matrix.postScale(newWidth / width, newHeight / height);
    
        // recreate the new Bitmap and set it back
        return Bitmap.createBitmap(bitmapToScale, 0, 0, bitmapToScale.getWidth(), bitmapToScale.getHeight(), matrix, true);  
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-12
      • 2013-08-24
      • 1970-01-01
      • 2014-02-28
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      相关资源
      最近更新 更多