Scaled Bitmap maintaining aspect ratio

后端 未结 12 854
-上瘾入骨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:29

    There is simple math involved in rescaling the image, consider the following snippet and follow along, 1. Suppose, you have Imaan image with 720x1280 and you want to to be fit in 420 width, get the percentage of reduction required by given math,

    originalWidth = 720;
    wP = 720/100;
    /*  wP = 7.20 is a percentage value */
    
    1. Now subtract the required width from original width and then multiply the outcome by wP. You will get the percentage of width being reduced.

    difference = originalWidth - 420; dP = difference/wP;

    Here dP will be 41.66, means you are reducing the size 41.66%. So you have to reduce the height by 41.66(dP) to maintain the ration or scale of that image. Calculate the height as given below,

    hP = originalHeight / 100;
    //here height percentage will be 1280/100 = 12.80
    height = originalHeight - ( hp * dP);
    // here 1280 - (12.80 * 41.66) = 746.75
    

    Here is your fitting scale, you can resize image/Bitmap in 420x747. It will return the resized image without losing the ratio/scale.

    Example

    public static Bitmap scaleToFit(Bitmap image, int width, int height, bool isWidthReference) {
        if (isWidthReference) {
            int originalWidth = image.getWidth();
            float wP = width / 100;
            float dP = ( originalWidth - width) / wP;
            int originalHeight = image.getHeight();
            float hP = originalHeight / 100;
            int height = originalHeight - (hP * dP);
            image = Bitmap.createScaledBitmap(image, width, height, true);
        } else {
            int originalHeight = image.getHeight();
            float hP = height / 100;
            float dP = ( originalHeight - height) / hP;
            int originalWidth = image.getWidth();
            float wP = originalWidth / 100;
            int width = originalWidth - (wP * dP);
            image = Bitmap.createScaledBitmap(image, width, height, true);
        }
        return image;
    }
    

    here you are simply scaling the image with reference of height or width parameter to fit into required criteria.

提交回复
热议问题