我正在开发一款包含许多图像作为 Sprite 的 Android 游戏。
当我按以下方式加载图像时:
public static Bitmap loadBitmap(int resId) {
return BitmapFactory.decodeResource(getResources(), resId, options);
}
一切正常。
当我尝试使用此代码缩小或放大位图时:
public static Bitmap loadBitmap(int resId) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId, options);
Matrix matrix = new Matrix();
matrix.postScale(0.8f, 0.8f);
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
bitmap = null;
return scaledBitmap;
}
应用程序崩溃并出现以下异常:
2211840-byte external allocation too large for this process.
Out of memory: Heap Size=4935KB, Allocated=2549KB, Bitmap Size=18463KB
VM won't let us allocate 2211840 bytes
为什么缩放会导致 OutOfMemory 异常?我什至尝试回收原始图像以节省一些空间。我没有故意使用 Bitmap.createScaledBitmap(...)
,因为此方法会在内部泄漏内存(如其他在线资源中所述)。
提前谢谢你,
兹拉特科
最佳答案
您可能非常接近内存限制。看起来您正在创建一个非常大的位图(我不确定为什么要使其与原始位图大小相同)。从日志中,您已经使用了 25MB 的 Java 分配和 18MB 的位图分配,因此您基本上正好达到 48MB 的堆限制。
此外,我认为 createScaledBitmap() 泄漏的可能性很小。它所做的基本上就是您在这里所做的。
关于android - Android中缩放图片导致OutOfMemory异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6158819/