2017-05-25 58 views
0

我知道,在Stackoverflow中有很多类似的问题。但我无法解决我的问题。如何解决OutofMemoryError错误? (After Bitmap.createScaledBitmap)

我有某种拼图游戏。 Drawable-nodpi文件夹中的图片为2500x1250。

我想用下面的代码来调整图像提示:

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, 
                int reqWidth, int reqHeight) { 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeResource(res, resId, options); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeResource(res, resId, options); 
} 

public static int calculateInSampleSize(
     BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 

     final int halfHeight = height/2; 
     final int halfWidth = width/2; 


     while ((halfHeight/inSampleSize) >= reqHeight 
       && (halfWidth/inSampleSize) >= reqWidth) { 
      inSampleSize *= 2; 
     } 
    } 

    return inSampleSize; 
} 

我这样称呼它:(我称这些代码几次)

private Bitmap resizeImg (int rsm) { 

    Bitmap bmp = decodeSampledBitmapFromResource(getResources(),rsm,wdth,hght); 

    return bmp; 
} 

我需要使用Matrix作为Imageview的缩放比例。但这不是我想要的尺寸。它的工作原理没有Matrix

我解决问题Matrix像这样:

Bitmap.createScaledBitmap

private Bitmap resizeImg (int rsm) { 

    Bitmap bmp = decodeSampledBitmapFromResource(getResources(),rsm,wdth,hght); 

    // return bmp; 

    Bitmap resized = Bitmap.createScaledBitmap(bmp, wdth,hght,true); //I get OutOfMemoryError this line. 
    return resized; 

} 

这种插入真正解决我的问题。但是,我每天都会收到很多OutOfMemoryError错误。

我需要做些什么来解决这个错误?请帮帮我。谢谢。

+0

尽量摆脱第一个'decodeResource的()'使用'inJustDecodeBounds = true'调用。您知道图像的大小,因为您在问题中提供了详细信息。我不知道'inJustDecodeBounds = true'对资源的作用有多好,既然你已经知道了大小,那么无论如何都会节省时间。 – CommonsWare

回答

0

1] largeHeap在Android清单是真正添加到您的应用程序标签:

  android:largeHeap="true" 

2]回收所有使用的位图,

Example: 
     bmp.recycle(); 
     resized.recycle(); 
+0

我已经在使用'android:largeHeap =“true”'。我会尝试其他代码并写出结果。谢谢。 – MhmKK

+0

但是可以肯定的是,在调用recycle()后你没有使用Bitmap实例,否则你将会得到“尝试使用循环位图”的异常&app将会崩溃。 –

+0

是的。我把注意力放在了代码上。该应用程序在市场上是最新的。比以前更少的错误。但是错误依然存在。我自己的测试设备上没有出现任何错误。 – MhmKK