我知道,在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