首先,问一个问题How to measure width of character precisely?这是回答,对于这种情况并没有真正的帮助,所以这不是那个的重复.
我有一根绳子。我画画使用graphics.DrawString
,但是当我需要在其后放置另一个字符串时,我需要知道前一个字符串的精确宽度。
为此,我使用graphics.MeasureString:
StringFormat format = new StringFormat(StringFormat.GenericTypographic);
format.Alignment = StringAlignment.Center;
format.Trimming = StringTrimming.None;
format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
我尝试过很多其他功能,就像TextRendered.MeasureText
然而,所有可能的参数组合都失败了。
提到的 MeasureString 组合最接近我需要的(它在大多数情况下都有效,特殊字符除外),但是使用像 # 这样的字符会破坏它。宽度要么更短,要么更长。
有没有办法获得 DrawString 函数生成的文本的精确大小? DrawString如何计算绘图区域的大小?它显然一定是其他函数,因为大小总是不同的。
整个应用程序的源代码在这里https://gitorious.org/pidgeon/pidgeon-main/(我使用这个的文件是https://gitorious.org/pidgeon/pidgeon-main/blobs/master/scrollback/SBABox.cs)
您只需要消除多余的宽度即可。您可以通过使用来做到这一点字符串格式:
GdipStringFormatGetGenericTypographic()
您还可以使用:
float doubleWidth = g.MeasureString(text+text,...).Width;
float singleWidth = g.MeasureString(text).Width;
float textWidth = doubleWidth-singleWidth;
这将允许您使用其他语言,例如日语.
在代码项目上,Pierre Anaud 的解决方案是使用MeasureCharacterRanges
,它返回与指定字符串的边界框完全匹配的区域:
static public int MeasureDisplayStringWidth(Graphics graphics, string text, Font font)
{
System.Drawing.StringFormat format = new System.Drawing.StringFormat ();
System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 0, 1000, 1000);
var ranges = new System.Drawing.CharacterRange(0, text.Length);
System.Drawing.Region[] regions = new System.Drawing.Region[1];
format.SetMeasurableCharacterRanges (ranges);
regions = graphics.MeasureCharacterRanges (text, font, rect, format);
rect = regions[0].GetBounds (graphics);
return (int)(rect.Right + 1.0f);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)