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.