Java 位图内存错误
我正在制作一个Android游戏,但是当我加载位图时,我得到了一个内存错误。我知道这是由一个非常大的位图(这是游戏背景)引起的,但我不知道如何避免出现“位图大小扩展VM预算”错误。我无法重新缩放位图使其变小,因为我无法使背景变小。有什么建议吗 哦,是的,下面是导致错误的代码:Java 位图内存错误,java,android,memory,bitmap,Java,Android,Memory,Bitmap,我正在制作一个Android游戏,但是当我加载位图时,我得到了一个内存错误。我知道这是由一个非常大的位图(这是游戏背景)引起的,但我不知道如何避免出现“位图大小扩展VM预算”错误。我无法重新缩放位图使其变小,因为我无法使背景变小。有什么建议吗 哦,是的,下面是导致错误的代码: space = BitmapFactory.decodeResource(context.getResources(), R.drawable.background); space = Bi
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... : ) */
希望有帮助。这可能会帮助您:
从Android开发者网站,一个关于如何高效显示位图和其他内容的教程 - 我不明白你为什么要使用
?背景资料。如果有必要,可以。否则请使用ImageBitmap
并设置其背景,因为您使用的是背景图像。 这很重要。(查看Android文档,他们已经明确指出了这个问题。)布局
Drawable d = getResources().getDrawable(R.drawable.your_background);
backgroundRelativeLayout.setBackgroundDrawable(d);
- 在大多数android设备中,意图大小等于16MB。你必须遵守这些指示
BitmapFactory.decodeStream
方法来获取资源或任何你能得到的东西:)