3

We can draw a text inside a rectangle easily.

enter image description here

Currently I would like to draw a text inside and FIT a rectangle.

enter image description here

Please help.

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
Paimiya
  • 105
  • 1
  • 7
  • what exactly does fit mean? you want the text having the same hight and the same width as the rectangle? – Mong Zhu Jul 26 '17 at 06:16
  • Yes you got it. The text string may be stretched according to the height and width of that rectangle. – Paimiya Jul 26 '17 at 06:29
  • Please post the code you're using for the first version, so that people can show you how to adapt it to the second version. – perigon Jul 26 '17 at 06:39

1 Answers1

9

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);
    }
}
C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72