如何使用Create Bitmap避免OUtOfMemory问题

时间:2014-11-25 16:41:38

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

我尝试使用以下代码从视图创建位图:

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

但我有 Out of Memory 问题。我可以通过将此选项添加到清单文件 android:largeHeap =" true" 来修复它,不推荐!!

我正在考虑回收视图,可能是一个解决方案吗?

这是printStack:

  

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:FATAL EXCEPTION:   主

1 个答案:

答案 0 :(得分:0)

我认为你会得到很多会使系统内存超载的Bitmaps,或者如果它只是一个人认为它是一个非常巨大的,那么,要解决这个问题,你必须做两件事, 第一次确保您不会为同一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);  

}