Click here to Skip to main content
15,884,962 members
Articles / Programming Languages / C#
Tip/Trick

Size to Fit

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
1 Jul 2016CPOL 7.6K   4  
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:

C++
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:

C++
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Wischner Ltd
United Kingdom United Kingdom
Writing code since 1982 and still enjoying it.

Comments and Discussions

 
-- There are no messages in this forum --