OutOfMemoryError /使用视图的尺寸创建背景图像

时间:2012-09-13 11:53:53

标签: android

每隔一段时间我就会看到一个类似于我的应用的崩溃报告:

java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=18119KB, Allocated=15536KB, Bitmap Size=31040KB)
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:695)
at myPackage.MyApp.MyView.onSizeChanged(MyView.java:46)

到目前为止,我无法重现此问题,并且没有关于出现此问题的设备的信息。

“位图大小= 31040KB”究竟是什么意思?我的应用程序是否真的试图创建一个30MB的位图? 我正在为自定义SeekBar组件创建一个背景图像,该组件应该具有相同的视图大小(9-patch不适合我的用例)。以下是产生错误的SeekBar的重写方法:

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    if (w <= 0 || h <= 0)
        return;

    LayerDrawable ld = (LayerDrawable)getContext().getResources().getDrawable(R.drawable.colorpicker);

    Bitmap output = Bitmap.createBitmap(w,
                h, Config.ARGB_8888);

    // code that draws the image, left that out here

    BitmapDrawable bmD = new BitmapDrawable(output);
    ld.setDrawableByLayerId(android.R.id.background, bmD);
    setProgressDrawable(ld);

    super.onSizeChanged(w, h, oldw, oldh);
}

第46行是创建位图的位置。 视图在整个屏幕上延伸并具有SeekBar的默认高度,因此在最坏的情况下,位图应该可能需要大约80KB ...任何想法可能出错?

1 个答案:

答案 0 :(得分:0)

尺寸位图宽度*高度* 4 =尺寸。可以帮到你:draw bitmap 试试这是代码,可能对你有帮助;

for(int i=0; i<5; i++){
try{
   Bitmap output = Bitmap.createBitmap(w,
                h, Config.ARGB_8888);     
   break;
}catch(OutOfMemmoryException e){
  e.printStackTrace();
   w -=50;
   h -=50;//or another numbers;
}
}