Say I have the string "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus arcu massa, tempus non tincidunt ut, tempus sit amet odio. Mauris in dui sed enim vulputate dictum."
I want that string wrapped by a specific length (in pixels) and without breaking words. 80 pixels for example.
I have the Font variable that is used to draw the string and the Graphics variable (often called "g") so I can measure the length of the string where needed.
All samples that I found only wrap text by character-length but I need it in pixels for GDI+ drawing. I do not want to use the TextRenderer control because it seems to bug. Sometimes it measures it's own text-height wrong. It's rare but it happens.
So far I got the following:
public static string WrapTextByPixels(string text, ref Graphics g, Font font, float maxWidth)
{
string[] originalLines = text.Split(new[] { " " }, StringSplitOptions.None);
var wrapBuilder = new StringBuilder();
float currentLineWidth = 0;
foreach (var item in originalLines)
{
float itemWidth = g.MeasureString(item, font).Width;
currentLineWidth += itemWidth;
if (currentLineWidth > maxWidth ||
itemWidth > maxWidth) // When a single word is longer than the maxWidth then just add it
{
wrapBuilder.Append(Environment.NewLine);
currentLineWidth = 0;
}
wrapBuilder.Append(item + " ");
}
return wrapBuilder.ToString();
}
But the above code doesn't work. Some lines are still too long.
You cannot bypass TextRenderer here, you must use its MeasureText() method so the calculated layout matches what is rendered, later, when the DrawText() method renders the text. Other ways to calculate string length, like Graphics.MeasureString() will just produce more error, the text layout for the Graphics class is very different. And pretty broken, the reason that TextRenderer was added in .NET 2.0
If you get bad results then that's almost always because you didn't specify the TextFormatFlags correctly. It must exactly match the flags that will be used in the DrawText() method call. That's not always easy to find out, especially when the text is drawn by painting code inside the framework. Use the Reference Source to find out.