gpt4 book ai didi

winforms - TextRenderer.MeasureText 的问题

转载 作者:行者123 更新时间:2023-12-04 16:21:46 25 4
gpt4 key购买 nike

嗨,我正在使用 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

最佳答案

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

关于winforms - TextRenderer.MeasureText 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2116216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com