views:

286

answers:

1

Hi I am using TextRenderer.MeasureText() method to measure the text width for a given font. I use Arial Unicode MS font for measuring the width, which is a Unicode font containing characters for all languages. The method returns different widths on different servers. Both machines have Windows 2003, and .net 3.5 SP1 installed.

Here is the code we used

using (Graphics g = Graphics.FromImage(new Bitmap(1, 1)))
{                
    width = TextRenderer.MeasureText(g, word, textFont, new Size(5, 5), TextFormatFlags.NoPadding).Width;
}

Any idea why this happens?

I use C# 2.0

+2  A: 

MeasureText is not known to be accurate.

Heres a better way :

    protected int _MeasureDisplayStringWidth ( Graphics graphics, string text, Font font )
    {
        if ( text == "" )
            return 0;

        StringFormat format = new StringFormat ( StringFormat.GenericDefault );
        RectangleF rect = new RectangleF ( 0, 0, 1000, 1000 );
        CharacterRange[] ranges = { new CharacterRange ( 0, text.Length ) };
        Region[] regions = new Region[1];

        format.SetMeasurableCharacterRanges ( ranges );
        format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;

        regions = graphics.MeasureCharacterRanges ( text, font, rect, format );
        rect = regions[0].GetBounds ( graphics );

        return (int)( rect.Right );
    }
Mongus Pong
Hey Thanks for the inputs... Let me try the same.
Amit
Hey That works fine..! Thanks a lot..
Amit