gpt4 book ai didi

android - 如何在 Android 中加载高分辨率位图?

转载 作者:行者123 更新时间:2023-11-29 21:13:18 26 4
gpt4 key购买 nike

我正在开发一个 Android 应用程序,在资源文件夹中我有一张分辨率为 8000x400px 的图像。这是一个 .png,我在我的 Sprite 类中使用它来模拟动物的运动。

我在我的 SurfaceView 类中使用 drawBitmap() 显示 png 的部分。

Sprite 类、SurfaceView 和所有元素都工作得很好,但是当处理那么大的图像时,它不会显示任何东西。

要解决这个问题我想知道。

  1. Bitmap 允许的最大分辨率限制是多少安卓?
  2. 如何在 onDraw() 中显示那个大小的 Sprite?

最佳答案

关于位图的显示/加载:

您需要正确加载Bitmap 并根据需要调整Bitmap 的大小。在大多数情况下,加载比设备屏幕支持的分辨率更高的位图是没有意义的。

此外,这种做法对于在处理如此大的Bitmaps 时避免OutOfMemoryErrors 非常重要。

例如,大小为 8000 x 4000 的位图使用超过 100 兆字节 的 RAM(32 位颜色),这对于移动设备来说是一个巨大的数量,远远超过即使是高端设备也能处理。

这是正确加载位图的方法:

public abstract class BitmapResLoader {

public static Bitmap decodeBitmapFromResource(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);
}

private 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;
}
}

代码中的示例用法:

Bitmap b = BitmapResLoader.decodeBitmapFromResource(getResources(),
R.drawable.mybitmap, 500, 500);

摘自此处的 Google Android 开发者指南: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

关于最大位图大小:

最大位图大小限制取决于底层 OpenGL 实现。使用 OpenGL 时,可以通过(来源:Android : Maximum allowed width & height of bitmap)进行测试:

int[] maxSize = new int[1];
gl.glGetIntegerv(GL10.GL_MAX_TEXTURE_SIZE, maxSize, 0);

例如对于 Galaxy S2,它是 2048x2048。

关于android - 如何在 Android 中加载高分辨率位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22130212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com