Search code examples
c#stringwinformstexttextrenderer

How to correctly measure characters in string using TextRenderer?


I am trying to draw a multi-colored string.

As there are no default methods to do this, I am trying to draw the string char by char myself using TextRenderer.DrawText, however, it does not report correctly first character width when I try to measure the string.

To draw it char by char I iterate through string measuring previous characters width to find the position of the next character to draw.

To get width, I use:

       TextRenderer.MeasureText(word.Substring(0, i),
                    drawFont,
                    new Size(int.MaxValue, int.MaxValue),
                    (TextFormatFlags.Left | TextFormatFlags.NoPadding)).Width

Which works normally but for the first character, which generates output like:

      L OREMIPSUM

Basically, if there is only one character - it measures it with padding despite my flags.

I can use:

      TextRenderer.MeasureText(String.Concat("*", chr.ToString(), "*"), font).Width - TextRenderer.MeasureText("**", font).Width

to measure the first character and get correct width value, but it feels like I am doing some hack when there should be a better way available.

I can also use string in the method above to avoid use of TextRenderer.MeasureText and still get correct results without the first character issue.

What would be a correct way to measure characters in my case?


Solution

  • You should use MeasureString from the graphics object. Also take a look at TextRenderer.MeasureText and Graphics.MeasureString mismatch in size. It will explain the difference.