我有个问题。我的主菜单/开始屏幕有一个大图形。这会导致某些旧设备出现内存不足异常。这是一个分辨率为 1920*1080 的 PNG 文件,我使用 ImageFormat RGB565。你有什么想法可以减少使用的内存吗?
2 回答
如前所述,您可以缩小图像,但如果由于某种原因您不想或不能这样做,您可能需要检查该链接:
http://developer.android.com/training/displaying-bitmaps/index.html
你也可以添加
largeHeap=true
为了增加一点内存,但它只适用于新设备,Android 2.x 不支持
这就是您要查找的内容:
BitmapFactory.Options.inSampleSize
如果设置为 true,则生成的位图将分配其像素,以便在系统需要回收内存时可以清除它们。在这种情况下,当需要再次访问像素时(例如,绘制位图,调用 getPixels()),它们将被自动重新解码。为了进行重新解码,位图必须能够访问编码数据,方法是共享对输入的引用或复制它。这种区别由 inInputShareable 控制。如果这是真的,那么位图可能会保留对输入的浅引用。如果这是错误的,那么位图将显式地复制输入数据,并保留它。即使允许共享,实现仍可能决定制作输入数据的深层副本。
来源:http: //developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize
因此,基本上您可以inSampleSize
根据屏幕分辨率和可用 RAM 进行调整,以便始终为给定设备提供足够版本的位图。这将防止OutOfMemoryError
发生错误。
以下是如何使用它的示例:
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) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
资料来源:http: //developer.android.com/training/displaying-bitmaps/load-bitmap.html 该链接下还有更多信息,因此我建议您查看一下。