views:

130

answers:

1

Hi,

If I have an image of which I know the height and the width, how can I fit it in a rectangle with the biggest possible size without stretching the image.

Pseudo code is enough (but I'm going to use this in Java).

Thanks.


So, based on the answer, I wrote this: but it doesn't work. What do 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, 0, 0, (int) (bi.getWidth() * scale), (int) (bi.getHeight() * scale), this);
}
if (rectRatio < imageRatio)
{
    // based on the height
    double scale = getHeight() / bi.getHeight();
    g.drawImage(bi, 0, 0 , (int) (bi.getWidth() * scale), (int) (bi.getHeight() * scale), this);
}
+4  A: 

Determine the aspect ratio of both (height divided by width, say, so tall, skinny rectangles have an aspect ratio > 1).

If your rectangle's aspect ratio is greater than that of your image, then scale the image uniformly based on the widths (rectangle width / image width).

If your rectangle's aspect ratio is less than that of your image, then scale the image uniformly based on the heights (rectangle height / image height).

John at CashCommons
Can you check out my update?
Martijn Courteaux
As far as I can tell, it looks like you're doing what I suggested, and I think I double-checked my logic. Are the values correct that you're grabbing at each step? (Are bi.GetWidth() and GetHeight() all giving you the right numbers?) (I'm not a Java programmer, but I did stay at a Holiday Inn Express last night! ;) )
John at CashCommons
I found it: I did not use doubles
Martijn Courteaux