65.9K
CodeProject is changing. Read more.
Home

Size to Fit

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Jul 1, 2016

CPOL
viewsIcon

7731

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