Reputation: 105
We can draw a text inside a rectangle easily.
Currently I would like to draw a text inside and FIT a rectangle.
Please help.
Upvotes: 3
Views: 3996
Reputation: 26456
I think the easiest way is to scale the graphics output to the destination rectangle:
public static class GraphicsExtensions
{
public static void DrawStringInside(this Graphics graphics, Rectangle rect, Font font, Brush brush, string text)
{
var textSize = graphics.MeasureString(text, font);
var state = graphics.Save();
graphics.TranslateTransform(rect.Left, rect.Top);
graphics.ScaleTransform(rect.Width / textSize.Width, rect.Height / textSize.Height);
graphics.DrawString(text, font, brush, PointF.Empty);
graphics.Restore(state);
}
}
Upvotes: 9