44

I am using pixels as the unit for my font. In one place, I am performing a hit test to check if the user has clicked within the bounding rectangle of some text on screen. I need to use something like MeasureString for this. Unfortunately, the code doing the hit test is deep within a library which does not have access to a Graphics object or even a Control.

How do I get the bounding box of a string given the font without using the Graphics class? Why do I even need a Graphics object when my font is in pixels?

2
  • What do you have if you don't have the Control? I'm assuming Font and the string, but is there anything else?
    – micahtan
    Jun 16, 2009 at 19:09
  • Nothing else. My library is a kind of a Scenegraph. I am trying to avoid dependencies on System.Drawing and System.Windows.Forms Jun 17, 2009 at 4:29

5 Answers 5

52

If you have a reference to System.Windows.Forms, try using the TextRenderer class. There is a static method (MeasureText) which takes the string and font and returns the size. MSDN Link

12
  • 3
    Slight problem with TextRenderer is that it uses integers for the return value, which can cause problems if you need sub-pixel precision. Otherwise, it's a good alternative. Sep 1, 2010 at 3:45
  • How is this the solution? The example in the link shows TextRenderer.DrawText(e.Graphics,
    – user153923
    Oct 3, 2012 at 19:01
  • 1
    @jp2code - Did you even read my answer? He asked how to measure a string without using the Graphics class. I suggested the MeasureText method on the TextRenderer class. It answers his question and I even provided the link to the MSDN documentation for this class. Take another look.
    – Jarrod
    Oct 5, 2012 at 4:02
  • 3
    @jp2code don't know if you still care but MeaureText uses an internal class WindowsGraphicsCacheManager. The manager has a static MeasurementGraphics property which gets inited on its first use. It does this by creating a graphics from the device context with a PInvoke to the gdi32.dll using this constructor. NerdFury's answer eventually uses this constructor and of course the Graphics isn't cached but otherwise they're the same Feb 26, 2013 at 20:58
  • 1
    @Jarrod well, I like to keep my forms related code separate from my drawing related code, and separate from code that has no dependencies except C#, etc. maybe I'm rendering text to an image or something in a command-line program or service or something. no reason that I should need a reference to windows forms, except that TextRenderer is there for some reason instead of in System.Drawing. Oct 26, 2018 at 23:29
26

You don't need to use the graphics object that you are using to render to do the measuring. You could create a static utility class:

public static class GraphicsHelper
{
    public static SizeF MeasureString(string s, Font font)
    {
        SizeF result;
        using (var g = Graphics.FromHwnd(IntPtr.Zero))
        {
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            result = g.MeasureString(s, font, int.MaxValue, StringFormat.GenericTypographic);
        }

        return result;
    }
}

It might be worthwhile, depending on your situation to set the dpi of the bitmap as well.

6
  • 1
    Looks good, but I dont think new Bitmap(0, 0) is allowed, maybe (1,1) May 18, 2010 at 4:42
  • 1
    @AlexanderN I just confirmed that Bitmap(0, 0) is invalid. Your solution of Bitmap(1, 1) is correct. Nov 3, 2011 at 14:40
  • image object could be an static to avoid recreated the object each time Jan 22, 2016 at 10:47
  • 11
    Use Graphics.FromHwnd(IntPtr.Zero) to avoid creating bitmap.
    – Raj
    May 25, 2017 at 19:51
  • 1
    Take care of using StringFormat.GenericTypographic to get correct sizes. Also use the same StringFormat in the DrawString method. See the Remarks section of MeasureString and this nice StackOverflow answer Jun 22, 2021 at 10:49
12

MeasureString method in @NerdFury answer will give a higher string width than expected.Additional info you can find here. If you want to measure only the physical length please add this two lines :

g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
result = 
  g.MeasureString(measuredString, font, int.MaxValue, StringFormat.GenericTypographic);
1

This example does great job of illustrating the use of FormattedText. FormattedText provides low-level control for drawing text in Windows Presentation Foundation (WPF) applications. You can use it to measure the Width of a string with a particular Font without using a Graphics object.

public static float Measure(string text, string fontFamily, float emSize)
{
    FormattedText formatted = new FormattedText(
        item, 
        CultureInfo.CurrentCulture, 
        System.Windows.FlowDirection.LeftToRight, 
        new Typeface(fontFamily), 
        emSize, 
        Brushes.Black);

    return formatted.Width;
}

Include WindowsBase and PresentationCore libraries.

1

This may not be but a repeat of others, but my problem was the unwanted Graphics object as well. After listening to the above frustrations I simply tried:

Size proposedSize = new Size(int.MaxValue, int.MaxValue);
TextFormatFlags flags = TextFormatFlags.NoPadding;
Size ressize = TextRenderer.MeasureText(content, cardfont, proposedSize, flags);

(where 'content' is the string to measure and cardfont the font it is in)

... and was in luck. I could use the result to set the width of my column in VSTO.

1
  • I found this solution more accurate on high resolutions screens but less accurate on lower resolution screens.
    – rboy
    Mar 2 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.