public static Size PreserveAspectRatioWithinBounds(this Size size, Size bounds) { var aspectRactio = size.Width / size.Height; var fitWidth = new Size(bounds.Width, bounds.Width / aspectRactio); var fitHeight = new Size(bounds.Height * aspectRactio, bounds.Height); return bounds.Contains(fitWidth) ? fitWidth : fitHeight; }