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

时间:2014-03-02 16:28:45

标签: android bitmap size resolution

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

我在png课程中使用drawBitmap()显示SurfaceView部分。

Sprite类,SurfaceView和所有元素都很完美,但是当处理那些大图像时,它不会显示任何内容。

要解决此问题,我想知道。

  1. 允许使用的位图的最大分辨率限制是多少? Android的?
  2. 如何在onDraw()中显示具有该尺寸的精灵?

1 个答案:

答案 0 :(得分:2)

关于显示/加载位图:

您需要正确加载Bitmap调整<{1}}的大小以满足您的需求。在大多数情况下,加载比设备支持的屏幕分辨率更高的位图是没有意义的。

此外,在使用Bitmap那么大的时候,这种做法对于避免OutOfMemoryErrors非常重要。

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

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

Bitmaps

代码中的示例用法:

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

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

关于最大位图大小:

最大位图大小限制取决于不确定的OpenGL实现。使用OpenGL时,可以通过(来源:Android : Maximum allowed width & height of bitmap):

进行测试
Bitmap b = BitmapResLoader.decodeBitmapFromResource(getResources(),
                                                      R.drawable.mybitmap, 500, 500);

e.g。对于Galaxy S2,它是2048x2048。