TextRenderer.MeasureText问题 [英] problem with TextRenderer.MeasureText

查看:542
本文介绍了TextRenderer.MeasureText问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



以下是我们使用的代码

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

任何想法为何发生这种情况?

我使用C#2.0

解决方案

MeasureText不准确。



继承人更好的方法:
$ b $ pre $ 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.SetMeasrableCharacterRanges(ranges);
format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;

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

return(int)(rect.Right);
}


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

解决方案

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

这篇关于TextRenderer.MeasureText问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆