locked
Determining Text Size RRS feed

  • Question

  • Is there a way to determine the size of a text string in WPF?  I'd like to take a given string, and have WPF calculate the size needed to render that string using a given font, style, etc. 

    Thanks.

    Bruce Bukovics
    Author of .NET 2.0 Interoperability Recipes
    http://www.apress.com/book/bookDisplay.html?bID=10116

    Thursday, June 1, 2006 8:54 PM

Answers

  • Use System.Windows.Media.FormattedText class. Set the style in the constructor and use Height/Width properties or, if you want the "exact" size, you can use BuildGeometry method.
    Friday, June 2, 2006 2:00 AM

All replies

  • I have a rather twisted solution for you...

    Place your string into a TextBox, set its width to "auto". Set its Font parameters to the desired values.

    Then, using the API from the TextBox, you can obtain the bounding rectangle of any of the characters, using the caret pos.... Take the X coord from before the first char and the X coord of past the last char and substract... Voila... Length of the string, the good ol' dirty way...

    I realize that this is a rather crappy solution... I did this hack once because I didn't really care for "beautifulness" and I did only a  "quick"  research for similar feature in the API.

    I'd be glad if anybody would share their own solution for this (particularly if its cleaner)...
    Thursday, June 1, 2006 9:33 PM
  • Use System.Windows.Media.FormattedText class. Set the style in the constructor and use Height/Width properties or, if you want the "exact" size, you can use BuildGeometry method.
    Friday, June 2, 2006 2:00 AM
  • The FormattedText did the trick.  Thanks for your help.

    Bruce
    Monday, June 5, 2006 8:24 PM
  • My solution:

    public static float MeasureString(string text, Font fontInfo)

    {

    Bitmap bitmap = (Bitmap)ResourcesManager.GetObject("some_image");

    IntPtr ptr = bitmap.GetHbitmap(Color.White);

    Image image = Image.FromHbitmap(ptr);

    Graphics g = Graphics.FromImage(image);

    SizeF size = g.MeasureString(text, fontInfo);

    return size.Width;

    }

    Tuesday, June 6, 2006 3:10 AM