繁体   English   中英

Android位图内存错误

[英]Bitmap Memory Error Android

我正在制作一个Android游戏,但是当我加载位图时,出现内存错误。 我知道这是由很大的位图引起的(这是游戏背景),但是我不知道如何避免出现“位图大小扩展VM预算”错误。 我无法重新缩放位图以使其更小,因为我无法使背景更小。 有什么建议么?

哦,是的,这是导致错误的代码:

space = BitmapFactory.decodeResource(context.getResources(),
            R.drawable.background);
    space = Bitmap.createScaledBitmap(space,
            (int) (space.getWidth() * widthRatio),
            (int) (space.getHeight() * heightRatio), false);

您将必须对图像进行采样。 您不能将其“缩小”到明显小于屏幕的大小,但是对于小屏幕等,它不必像大屏幕一样具有高分辨率。

长话短说,您必须使用inSampleSize选项进行降采样。 如果图像适合屏幕,实际上应该很容易:

    final WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    final Display display = wm.getDefaultDisplay();

    final int dimension = Math.max(display.getHeight(), display.getWidth());

    final Options opt = new BitmapFactory.Options();
    opt.inJustDecodeBounds = true;

    InputStream bitmapStream = /* input stream for bitmap */;
    BitmapFactory.decodeStream(bitmapStream, null, opt);
    try
    {
        bitmapStream.close();
    }
    catch (final IOException e)
    {
        // ignore
    }

    final int imageHeight = opt.outHeight;
    final int imageWidth = opt.outWidth;

    int exactSampleSize = 1;
    if (imageHeight > dimension || imageWidth > dimension)
    {
        if (imageWidth > imageHeight)
        {
            exactSampleSize = Math.round((float) imageHeight / (float) dimension);
        }
        else
        {
            exactSampleSize = Math.round((float) imageWidth / (float) dimension);
        }
    }

    opt.inSampleSize = exactSampleSize; // if you find a nearest power of 2, the sampling will be more efficient... on the other hand math is hard.
    opt.inJustDecodeBounds = false;

    bitmapStream = /* new input stream for bitmap, make sure not to re-use the stream from above or this won't work */;
    final Bitmap img = BitmapFactory.decodeStream(bitmapStream, null, opt);

    /* Now go clean up your open streams... : ) */

希望能有所帮助。

这可能对您有帮助: http : //developer.android.com/training/displaying-bitmaps/index.html

来自Android开发者网站的有关如何有效显示位图和其他内容的教程。 =]

  • 我不明白您为什么要使用ImageBitmap 为背景。 如果有必要,没关系。 否则,请使用Layout并设置其背景,因为您使用的是背景图片。 这个很重要。 (查看Android文档。他们已经明确指出了这个问题。)

您可以按照以下方式进行操作

 Drawable d = getResources().getDrawable(R.drawable.your_background);
 backgroundRelativeLayout.setBackgroundDrawable(d);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM