Scale and retain aspect ratio

29 11 2008

After doing a bit of work on my level select menu, I came across the need to resize a texture to fit inside the a preview pane I’d created. However, not all of my preview images are going to be the same size or aspect ratio, nor do I want to enforce that restriction. I do, however, want to scale the images (up or down) to fit the pane without stretching them.

It’s a relatively simple procedure:

public static Vector2 FixAspectRatio(int imageX, int imageY, Vector2 paneDimensions)
            float imageAspectRatio = (float) imageX / imageY;

            float paneImageAspectRatio = paneDimensions.X / paneDimensions.Y;

            if (imageAspectRatio > paneImageAspectRatio)
                paneDimensions.Y = (paneDimensions.X / imageX) * imageY;
                paneDimensions.X = (paneDimensions.Y / imageY) * imageX;

            return paneDimensions;

So given a restricted pane size (here “paneDimensions”) and the size of the image, you’ll get back a scaled size. The scaled size will have the same aspect ratio as the image dimensions. It will also be no bigger than the given paneDimensions in width or height.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: