Android缩小图像总是最终拉长

时间:2015-07-08 15:06:14

标签: android imageview image-resizing

我正在尝试缩小高分辨率图像,例如大约1980x1080尺寸并在nexus 5 api 21+中模拟,我需要将此高分辨率图像加载到我的图像视图中。

我使用下面的位图代码

        float imageRatio = (float) newWidth / newHeight;

        int imageWidth = mybitmapimage.getWidth();
        int imageHeight = mybitmapimage.getHeight();

        float aspectRatio = (float) imageWidth / imageHeight; // original iamge

        // Initializing to find which needs scale down
        float scaleWidth = newWidth;
        float scaleHeight = newHeight;

        if (imageRatio < aspectRatio) {
            scaleHeight = ((float) newWidth) / aspectRatio;
        } else {
            scaleWidth = ((float) newHeight) * aspectRatio;
        }

        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP

        matrix.postScale(scaleWidth, scaleHeight);

        // "RECREATE" THE NEW BITMAP
        Bitmap resizedBitmap = Bitmap.createBitmap(
                bm, 0, 0, imageWidth, imageHeight, matrix, false);
        return resizedBitmap;

对于我的生活,这段代码总是得到拉伸或裁剪。源图像文件大约是1920 * 1080,所以缩小了。

如果有人能帮我解决这个扭曲的问题,我会非常感激。

1 个答案:

答案 0 :(得分:0)

ratio = Math.min(newWidth/oldWidth, newHeight/oldHeight);

That's how you get a scaling ratio to resize a bitmap while keeping the aspect ratio.

The final width and height are then:

finalWidth = oldWidth * ratio;
finalHeight = oldHeight * ratio;

Just use that ratio in your scale matrix:

matrix.postScale(ratio, ratio);