简体   繁体   中英

Graphics.Drawstring WordWrap is not as expected

In my billing application, bills are printed using Graphics.DrawString method, etc. When using Graphics.DrawString with word wrap to draw the ItemName it wrap words into many lines. so it is consuming many rows.

I recreated the problem using simple code. With this code I'm expecting output like the following image: Expected Output designed using MS Paint

This is my sample code.

 string FONTNAME = "Tahoma";
 text = "C# is a simple, modern, general-purpose, object-oriented programming language";
 e.Graphics.DrawString(text, new Font(FONTNAME, 12, FontStyle.Bold), drawBrush, new RectangleF(0, 0, 100.0F, 200F), new StringFormat());
 e.Graphics.DrawRectangle(new System.Drawing.Pen(drawBrush), 0, 0, 100.0F, 200F);

But I'm getting the following output: Output Image

Is there any option to break the words instead of word wrap ?

No, Graphics.DrawString does not have any option to break on characters (as opposed to whole words).

To control wrapping, you can pass a StringFormat object initialised with a StringFormatFlags . The only relevant flag is StringFormatFlags.NoWrap . The .NET documentation isn't very helpful, but if we look at the GDI+ documentation (which is the underlying library), we read:

StringFormatFlagsNoWrap

Specifies that the wrapping of text to the next line is disabled. … When drawing text within a rectangle, by default, text is broken at the last word boundary that is inside the rectangle's boundary and wrapped to the next line.

Thus, the only options are wrapping at word boundaries, or performing no wrapping at all.

To get the output you want, you will need to measure character-by-character and draw multiple strings (one for each line).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM