TextRenderer.MeasureText存在问题

时间:2010-01-22 09:25:40

标签: winforms graphics .net-2.0 gdi+

您好我正在使用TextRenderer.MeasureText()方法来测量给定字体的文本宽度。我使用Arial Unicode MS字体来测量宽度,这是一种包含所有语言字符的Unicode字体。该方法在不同的服务器上返回不同的宽度。这两台机器都安装了Windows 2003和.net 3.5 SP1。

以下是我们使用的代码

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

知道为什么会这样吗?

我使用C#2.0

3 个答案:

答案 0 :(得分:12)

//--------------------------------------------------------------------------------------
// MeasureText always adds about 1/2 em width of white space on the right,
// even when NoPadding is specified. It returns zero for an empty string.
// To get the precise string width, measure the width of a string containing a
// single period and subtract that from the width of our original string plus a period.
//--------------------------------------------------------------------------------------

public static Size MeasureText(string Text, Font Font) {
  TextFormatFlags flags
    = TextFormatFlags.Left
    | TextFormatFlags.Top
    | TextFormatFlags.NoPadding
    | TextFormatFlags.NoPrefix;
  Size szProposed = new Size(int.MaxValue, int.MaxValue);
  Size sz1 = TextRenderer.MeasureText(".", Font, szProposed, flags);
  Size sz2 = TextRenderer.MeasureText(Text + ".", Font, szProposed, flags);
  return new Size(sz2.Width - sz1.Width, sz2.Height);
}

答案 1 :(得分:11)

不知道MeasureText是否准确。

这是一个更好的方式:

    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 );
    }

答案 2 :(得分:1)

几年前我们遇到了类似的问题。在我们的例子中,出于某种原因,我们在两台不同的机器上安装了不同版本的相同字体。操作系统版本相同,但字体不同。

由于您通常不会在应用程序设置中部署系统字体,因此根据字体版本,测量和输出结果可能因机器而异。

既然你说......

  

并非所有机器都只返回其中的一些值。!

......这是我要检查的内容。

相关问题