我正在开发包含许多图像为精灵的Android游戏。在Android中缩放图像会导致OutOfMemory异常
当我加载图像的方式如下:
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
为什么结垢造成内存溢出的例外?我甚至尝试回收原始图像以节省一些空间。我没有故意使用Bitmap.createScaledBitmap(...)
,因为此方法会在内部泄漏内存(如其他在线资源中所述)。
谢谢你在前进,
兹拉特科
为什么第一个代码片段永远不会导致OOM异常?事实上,在第二个片段中,我将原始位图缩放到其大小的80%。分配,有2.5MB,而不是25MB – Bart 2011-05-28 00:54:33