Java – fit image to rectangle

If I have an image that I know the height and width, how can I put it in the largest rectangle without stretching the image

Pseudocode is enough (but I'll use it in Java)

thank you.

So, according to the answer, I wrote: but no What did I do wrong

double imageRatio = bi.getHeight() / bi.getWidth();
double rectRatio = getHeight() / getWidth();
if (imageRatio < rectRatio)
{
    // based on the widths
    double scale = getWidth() / bi.getWidth();
    g.drawImage(bi,(int) (bi.getWidth() * scale),(int) (bi.getHeight() * scale),this);
}
if (rectRatio < imageRatio)
{
    // based on the height
    double scale = getHeight() / bi.getHeight();
    g.drawImage(bi,this);
}

Solution

Determine the aspect ratio of the two (height divided by width, for example, height, thin rectangle has an aspect ratio of > 1)

If the aspect ratio of the rectangle is greater than the aspect ratio of the image, the image is scaled evenly according to the width (rectangle width / image width)

If the aspect ratio of the rectangle is less than the aspect ratio of the image, the image is scaled evenly according to the height (rectangle height / image height)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>