1

I have such model of image https://i.stack.imgur.com/ulLTS.jpg

I need to print text in the yellow box.

The problem is how to enable word wrap in graphics DrawString? My code:

    using (Graphics g = Graphics.FromImage(pictureBox1.Image))
    {
        Font drawFont = new Font("Arial", 16);
        SolidBrush drawBrush = new SolidBrush(Color.Black);
        g.DrawString("test text; test text;test text;test text", drawFont, drawBrush, new Point(240, 250));
    }
    pictureBox1.Image.Save("Image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

text that I print overflows

user3740163
  • 21
  • 1
  • 3
  • 1
    I'm pretty sure there is a `DrawString` overload that takes a `Rectangle` this will wrap text to that boundary – sa_ddam213 Jun 14 '14 at 10:54
  • Helps if you think it through for a bit, it of course cannot wrap anything if you don't tell it how wide the text is allowed to be. Only use Graphics.DrawString() on high resolution devices/images, you typically should be using TextRenderer.DrawText() and TextFormatFlags.WordBreak. – Hans Passant Jun 14 '14 at 11:32
  • [Similar question](https://stackoverflow.com/q/9507842/1997232) asked earlier (to link them, not sure if it's worth to mark as duplicate or merge). – Sinatr Aug 17 '17 at 13:59

1 Answers1

3

The DrawString method has an overload where you can pass in the bounding box the text has to fit in.

Your code should look something like this:

       g.DrawString("test text; test text;test text;test text", drawFont, drawBrush, new RectangleF(240f, 250f, endPointX, endPointY));
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325