在Android中显示位图图像的最佳实践

时间:2013-12-29 10:51:56

标签: android image bitmap imageview

我对Android显示位图图像的最佳实践感到困惑。我想在屏幕上显示一个图像。我对图像的属性(如分辨率,高度,宽度等)一无所知。我希望图像应该在任何设备和任何模式(端口或陆地)中显示。

这就是我目前正在做的事情:

  1. 首先找出设备的高度和宽度
  2. 然后相应地设置ImageView的高度和宽度。我的要求是我想使用50%的屏幕来显示图像。
  3. 最后使用以下方法显示位图

    private Bitmap checkBitmapDetails(){
        Bitmap bitmap;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inScreenDensity = 0;
    
        bitmap = BitmapFactory.decodeResource(getResources(),
                whichImage, options);
    
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, PREFERRED_WIDTH,
                PREFERRED_HEIGHT);
    
        options.inJustDecodeBounds = false;
    
        bitmap = BitmapFactory.decodeResource(getResources(),
                whichImage, options);
        bitmap = Bitmap.createScaledBitmap(bitmap, PREFERRED_WIDTH, PREFERRED_HEIGHT, true);
        return bitmap;
    }
    
    private 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) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
    
            // Calculate the largest inSampleSize value that is a power of 2 and
            // keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
    
        return inSampleSize;
    }
    
  4. 现在,如果源图像太大,我首先缩小图像,然后最后调用Bitmap.createScaledBitmap将图像缩放到我的首选高度和宽度。

    当我在开发者Android网站上阅读最佳实践时,硬编码高度和宽度并不好。我没有做硬编码,但我正在以编程方式操作高度和宽度。你怎么想,这是正确的我在做什么?

    我可以为drawable-hdpi,ldpi,mdpi,xhdpi,xxhdpi提供不同大小的图像。但是不同画面的图像大小是多少?

    请告诉我您认为最佳方法是什么。感谢。

0 个答案:

没有答案