2017-05-25 32 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