tags:

views:

475

answers:

2

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?

+5  A: 

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

Jarrod
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.
Raymond Martineau
+1  A: 

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 image = new Bitmap(0, 0))
        {
            using (var g = Graphics.FromImage(image))
            {
                result = g.MeasureString(s, font);
            }
        }

        return result;
    }
}

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

NerdFury
Looks good, but I dont think new Bitmap(0, 0) is allowed, maybe (1,1)
AlexanderN