C#|.NET : Scale With Aspect Ratio

Scaling
This is a simple extension method for class Size which returns a Size object, scaled to given bounding box, again a Size object. For example, in Scale Up in the picture above, you have a rectangular size with dimension – 93 X 37 (green) and you want it to scale up, maintaining aspect ratio, but not out of another rectangular size of dimension – 200 X 200 (pink). With following code, the extension method will return a Size object with scaled dimensions 200 X 79 (blue):

Size MySize = new Size(93, 37);
Size ScaledSize = MySize.MaintainAspectAndScale(new Size(200,200));

Similarly, in Scale Down in the picture above, you have a rectangular size with dimension – 267 X 344 (green) and you want it to scale down, maintaining the aspect ratio, into the size of dimension – 200 X 200 (pink). With following code, the extension method will return a Size object with scaled dimensions 200 X 155 (blue):

Size mySize = new Size(267, 344);
Size scaledSize = MySize.MaintainAspectAndScale(new Size(200,200));

Size.MaintainAspectAndScale

    public static class GeometryExtensions
    {
        public static Size MaintainAspectAndScale(this Size Source, Size ScaleTo)
        {
            Size returnSize = Source;
            double scaleTo = ScaleTo.Height < ScaleTo.Width ? ScaleTo.Height : ScaleTo.Width;
            double resizeFactor = 1;
            if (Source.Height >= Source.Width) //source size is portrait or square
            {
                resizeFactor = (scaleTo - Source.Height) / Source.Height;
            }
            else //source size is landscape
            {
                resizeFactor = (scaleTo - Source.Width) / Source.Width;
            }
            returnSize.Height = Source.Height + (Source.Height * resizeFactor);
            returnSize.Width = Source.Width + (Source.Width * resizeFactor);
            return returnSize;
        }
    }

Get the code in my GitHub repository (POCs)!

Advertisements

One thought on “C#|.NET : Scale With Aspect Ratio

  1. Pingback: C# | .NET Extension Methods | Sharp Statements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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