Scaled Bitmap maintaining aspect ratio

后端 未结 12 925
-上瘾入骨i
-上瘾入骨i 2020-11-30 23:49

I would like to scale a Bitmap to a runtime dependant width and height, where the aspect ratio is maintained and the Bitmap fills the entire width

12条回答
  •  无人及你
    2020-12-01 00:34

    My solution was this, which maintains aspect ratio, and requires only one size, for example if you have a 1920*1080 and an 1080*1920 image and you want to resize it to 1280, the first will be 1280*720 and the second will be 720*1280

    public static Bitmap resizeBitmap(final Bitmap temp, final int size) {
            if (size > 0) {
                int width = temp.getWidth();
                int height = temp.getHeight();
                float ratioBitmap = (float) width / (float) height;
                int finalWidth = size;
                int finalHeight = size;
                if (ratioBitmap < 1) {
                    finalWidth = (int) ((float) size * ratioBitmap);
                } else {
                    finalHeight = (int) ((float) size / ratioBitmap);
                }
                return Bitmap.createScaledBitmap(temp, finalWidth, finalHeight, true);
            } else {
                return temp;
            }
        }
    

提交回复
热议问题