title: C# GDI+ wrap text (w/o TextRenderer)
body: <p>Say I have the string <em>"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."</em></p>
  
  <p>I want that string wrapped by a specific length (<strong>in pixels</strong>) and without breaking words. 80 pixels for example.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p><strong>So far I got the following:</strong></p>
  
  <pre><code>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 &gt; maxWidth ||
                      itemWidth &gt; 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();
          }
  </code></pre>
  
  <p>But the above code doesn't work. Some lines are still too long.</p>