• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 972
  • Last Modified:

MeasureString result is not presize

I use the following function to draw text with background:

        void DrawStringWithBackground(
            Graphics g, string text, Font font, Brush brushText,
            int x, int y, Brush brushBackground)
        {
            SizeF size = g.MeasureString(text, font);
            g.FillRectangle(brushBackground, x, y, (int)size.Width, (int)size.Height);

            g.DrawString(text, font, brushText, x, y);
        }

The problem is that MeasureString doesn't give 100% correct result, and background rectangle is too wide. Odd pixels can contain one additional character. How can I fix this?
TextRenderer gives better results, but I cannot use it, because the same code is used for printing. I can use also API for this, but I am looking for .NET solution.
0
AlexFM
Asked:
AlexFM
1 Solution
 
pgloorCommented:
Have you tried using one of the MeasureString methods that takes a format and set the format to MeasureTrailingSpaces ?

     void DrawStringWithBackground(
      Graphics g,
      string text,
      Font font,
      Brush brushText,
      int x, int y,
      Brush brushBackground) {

      StringFormat format = new StringFormat(StringFormat.GenericTypographic);
      format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;

      PointF origin = new PointF(x,y);

      SizeF size = g.MeasureString(text, font, origin, format );
      g.FillRectangle(brushBackground, x, y, (int)size.Width, (int)size.Height);

      g.DrawString(text, font, brushText, x, y);
    }

Not sure, but I remember about a problem with incorrect calculation if certain fontstyles are used (e.g. underlines).

Peter
0
 
AlexFMAuthor Commented:
Great, thank you very much.
BTW, I don't use underline and string doesn't contain trailing spaces, but result is much better.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now