Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Size to Fit

0.00/5 (No votes)
1 Jul 2016 1  
Size the child rectangle so that it fits into given parent rectangle, without distorting it

Problem

We would like to find the scale factor by which we need to multiply childs' width and height to fit into parent.

Algorithm

First, test if factor calculated from height...

...makes the width fit. If it doesn't (i.e. child width * scale factor > parent width), then use...

The Code

Calculate the scale factor like this:

private float ScaleFactor(RectangleF parent, RectangleF child)
{
    float factor = parent.Height / child.Height;
    if (child.Width * factor > parent.Width) // Switch!
        factor = parent.Width / child.Width;
    return factor;
}

In the paint procedure, use it like this:

Image image;
RectangleF imageRectangle;
Graphics graphics;
// ...
// Somehow populate image, imageRectangle, and graphics
// ...
float f = ScaleFactor(ClientRectangle,imageRectangle);
graphics.ScaleTransform(f, f);
graphics.DrawImage(image,Point.Empty);

History

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here