Android的大小调整位图保持宽高比位图、大小、Android

2023-09-05 02:58:20 作者:走不出的孤單

我有一个自定义视图(1066 x 738),和我传递一个位图图像(720x343)。我希望以位图以适应自定义视图不超出界父。

I have a custom view (1066 x 738), and I am passing a bitmap image (720x343). I want to scale the bitmap to fit in the custom view without exceeding the bound of the parent.

我要实现的是这样的:

我应该如何计算位图大小?

How should I calculate the bitmap size?

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

How I calculate the new width/height:

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

但是,所有我实现是这样的:

But all I am achieving is this:

推荐答案

您应该尝试使用内置的 ScaleToFit.CENTER 的转换矩阵。例如:

You should try using a transformation matrix built for ScaleToFit.CENTER. For example:

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