Android resize bitmap keeping aspect ratio [duplicate]

拜拜、爱过 提交于 2019-12-18 12:56:10

问题


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.

I want to achieve something like this:

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:


回答1:


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


来源:https://stackoverflow.com/questions/24961797/android-resize-bitmap-keeping-aspect-ratio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!