Fits this rectangle inside a containing rectangle, preserving aspect ratio.

The size is determined by the fit type. You can choose to map the width of this rectangle into the width of the destination, or the height into the height of the destination, or both. The rectangle will be centered inside the containing rectangle.

Syntax

[C#]

static RectangleF FitIn(RectangleF container, RectangleF contained, FitType fit);

[Visual Basic]

Shared Function FitIn(container As RectangleF, contained As RectangleF, fit As FitType) As RectangleF
Params
Name Description
container The rectangle into which to fit the contained rectangle.
contained The rectangle which should be contained.
fit The type of fit to apply.
return The resultant rectangle.
Notes

None.

Example

Here we center an image in a Bitmap:

  • We fit the width to the width of the Bitmap.
  • We fit the height to the height of the Bitmap.
  • We fit the width and height but do not allow the source image to increase in size.

[C#]using (Image image = Bitmap.FromFile(Server.MapPath("rez/david-bruyndonckx-F_hft1Wiyj8-unsplash.jpg"))) {
  foreach (FitType fit in new FitType[] { FitType.Width, FitType.Height, FitType.WidthAndHeightNoEnlargement }) {
    using (Bitmap bm = new Bitmap(640, 480)) {
      using (Graphics graphics = Graphics.FromImage(bm)) {
        graphics.Clear(Color.DeepSkyBlue);
        RectangleF rect = RectangleF.FitIn(bm.Bounds, image.Bounds, fit);
        graphics.DrawImage(image, rect);
      }
      bm.Save(Server.MapPath($"IG8_RectangleF_FitIn_{fit}.png"));
    }
  }
}



david-bruyndonckx-F_hft1Wiyj8-unsplash.jpg


IG8_RectangleF_FitIn_Width.png


IG8_RectangleF_FitIn_Height.png


IG8_RectangleF_FitIn_WidthAndHeightNoEnlargement.png