OutOfMemoryError虽然我缩小了位图的比例

时间:2014-09-24 07:19:30

标签: android bitmap imageview out-of-memory android-resources

我使用小资源图像(最大25kb,最大256x256)并使用毕加索从互联网加载一些较大的图像。直到现在,毕加索的装载从未失败过。但有时会加载资源图像。

对于资源图片,我使用附加的代码(setBitmap),但是虽然我缩小了图像比例,但在某些设备上,我的应用在调用OutOfMemoryError时仍会产生BitmapFactory.decodeResource。有没有人有想法,下一步去哪看?

private static void setBitmap(final ImageView iv, final int resId)
{
    iv.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
    {
        public boolean onPreDraw()
        {
            iv.getViewTreeObserver().removeOnPreDrawListener(this);
            iv.setImageBitmap(decodeSampledBitmapFromResource(iv.getContext().getResources(), resId, iv.getMeasuredWidth(), iv.getMeasuredHeight()));
            return true;
        }
    });
}

private static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int w, int h)
{
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    options.inSampleSize = calculateInSampleSize(options, w, h);

    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

private static int calculateInSampleSize(BitmapFactory.Options options, int w, int h)
{
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > h || width > w)
    {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        while ((halfHeight / inSampleSize) > h && (halfWidth / inSampleSize) > w)
        {
            inSampleSize *= 2;
        }
    }

    L.d(ImageTools.class, "inSampleSize | height | width: " + inSampleSize + " | " + height + " | " + width);

    return inSampleSize;
}

3 个答案:

答案 0 :(得分:1)

如果你有一个ImageViews列表,你可以实现一个缓存: http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

答案 1 :(得分:0)

您可以在清单中使用android:largeHeap="true"作为最后一个选项。 但是我不建议使用它,因为它可以使你的应用程序变慢。

答案 2 :(得分:0)

您可以使用

申请更多memory
 android:largeHeap="true"
清单中的

另外,您可以使用本机内存(NDK和JNI),因此您实际上绕过了堆大小限制。

这里有一些关于它的帖子:

这是一个为它制作的图书馆:

快乐编码

关于maven

相关问题