Android调整位图保持宽高比

Zba*_*ian 15 android bitmap scale

我有一个自定义视图(1066 x 738),我传递的是位图图像(720x343).我想缩放位图以适应自定义视图,而不超过父级的边界.

在此输入图像描述

我希望实现这样的目标:

在此输入图像描述

我该如何计算位图大小?

我如何计算新的宽度/高度:

    public static Bitmap getScaledBitmap(Bitmap b, int reqWidth, int reqHeight)
    {
        int bWidth = b.getWidth();
        int bHeight = b.getHeight();

        int nWidth = reqWidth;
        int nHeight = reqHeight;

        float parentRatio = (float) reqHeight / reqWidth;

        nHeight = bHeight;
        nWidth = (int) (reqWidth * parentRatio);

        return Bitmap.createScaledBitmap(b, nWidth, nHeight, true);
    }
Run Code Online (Sandbox Code Playgroud)

但我所取得的成就是:

在此输入图像描述

mat*_*ash 60

您应该尝试使用为其构建的转换矩阵ScaleToFit.CENTER.例如:

Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, b.getWidth(), b.getHeight()), new RectF(0, 0, reqWidth, reqHeight), Matrix.ScaleToFit.CENTER);
return Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true);
Run Code Online (Sandbox Code Playgroud)