Android调整位图保持宽高比

时间:2014-07-25 17:56:34

标签: android bitmap scale

我有自定义视图(1066 x 738),我正在传递位图图像(720x343)。我想缩放位图以适应自定义视图,而不超过父级的界限。

enter image description here

我想实现这样的目标:

enter image description here

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

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

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

但我所取得的就是:

enter image description here

1 个答案:

答案 0 :(得分: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);