我知道,在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錯誤。
我需要做些什麼來解決這個錯誤?請幫幫我。謝謝。
儘量擺脫第一個'decodeResource的()'使用'inJustDecodeBounds = true'調用。您知道圖像的大小,因爲您在問題中提供了詳細信息。我不知道'inJustDecodeBounds = true'對資源的作用有多好,既然你已經知道了大小,那麼無論如何都會節省時間。 – CommonsWare