加载大背景图片时出现内存不足错误。

23 浏览
0 Comments

加载大背景图片时出现内存不足错误。

我正在使用android:background为Android布局设置背景图片。
\n在放置一些图片后,我遇到了以下异常:
\n

08-24 00:40:19.237: E/dalvikvm-heap(8533): Out of memory on a 36000016-byte allocation.

\n
我该如何在Android上使用大尺寸的图片作为背景?
\n我能够扩展应用堆内存吗?或者这样做是不好的吗?

0
0 Comments

问题的原因是在加载大背景图像时出现了OutOfMemory错误。解决方法是创建一个drawable-nodpi文件夹,并将背景图像放入其中。然后使用Picasso库来显示图像,并使用.fit()和.centerCrop()方法对图像进行缩放。如果内存不足,Picasso将不会显示图像,而不是报错。希望这能帮到你!

0
0 Comments

问题原因:将背景图像放在drawable文件夹中,系统会根据屏幕密度对图像进行缩放,导致内存开销过大。

解决方法:

1. 在每个drawable文件夹中放置背景图像的特定版本(mdpi、hdpi、xhdpi等)。

2. 将背景图像放置在名为"drawable-nodpi"的特殊资源文件夹中。系统不会尝试对放置在此目录中的图像进行缩放,因此只会进行拉伸处理,分配的内存将与预期相同。

希望对您有所帮助。这使得我的图形内存分配减少了一半!谢谢!

0
0 Comments

在加载大型背景图像时,可能会遇到OutOfMemory错误。造成这个问题的原因是内存使用过多。为了解决这个问题,可以采取以下方法:

1. 尽量将背景图像的尺寸保持较小,可以通过剪裁图像使其适应屏幕,或在使用图像之前使用Photoshop等工具进一步压缩图像。

2. 使用下面的方法加载位图:

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;
    if (height > reqHeight || width > reqWidth) {
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    return inSampleSize;
}

3. 在使用完位图后,立即调用`recycle()`方法释放位图,并将引用设置为null,以确保内存中只有一个位图实例。

4. 确保所设置为背景的图像被正确加载(如裁剪为适应屏幕尺寸),并在不再需要时立即释放内存。

感谢Adam Stelmaszczyk提供的代码。

设置引用为null的意思是在使用完位图后,将该位图的引用设置为null,这样可以告诉系统该位图不再被使用,从而释放内存。

0