May 25, 2005

Draw Image To Fit A Rectangular Area

Following code draws an image scaled to a given rectangle, keeping the aspect ratio and centering the scaled image inside the rectangle using GDI+

 
  Graphics.DrawImage(image, FitToRect(this.ClientRectangle, image.Size));
 
 /// <summary>
 /// Fit the given src Size to the target Rectangle keeping the aspect
 /// ratio and centering the src inside the rectangle
 /// </summary>
 /// <param name="target"></param>
 /// <param name="src"></param>
 /// <returns></returns>
 static public Rectangle FitToRect(Rectangle target, Size src)
 {
    // Find the scale to fit the Src to the Target height
    float   sfh = (float)target.Height/(float)src.Height;
    // Find the scale to fit the Src to the Target width
    float   sfw = (float)target.Width/(float)src.Width;
    // Smaller of the 2 is the fit to view scale factor
    float   sf = Math.Min(sfh, sfw);
    // Find the size of the Src scaled to fit the target rectangle
    Size sizeToFit = new Size((int)Math.Round((double)src.Width*sf),
     (int)Math.Round((double)src.Height*sf) );
    Poiny loc = new Point((target.Width-sizeToFit.Width)/2,
                                    (target.Height-sizeToFit.Height)/2);
    // Now centre the scaled src size in the rectangle
    Rectangle rect = new Rectangle(loc, sizeToFit);
    return rect;
  }

No comments: