下面函数是经常用到的计算字串长度的方法:
private double MeasureTextWidth(String str, string fontName, double fontsize, double width)
{
double width = -1;
try
{
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromHwnd(m_hWnd);
graphics.PageUnit = System.Drawing.GraphicsUnit.Point;
System.Drawing.Font font = new System.Drawing.Font(fontName, (float)fontsize);
System.Drawing.SizeF size = graphics.MeasureString(str, font);
width = size.width;
font.Dispose();
graphics.Dispose();
}
catch (System.Exception e)
{
}
return width;
}
但是事实上,Graphics.MeasureString并不可靠,在不同的SKU下得到的结果会不同,原因不明,可能跟显卡驱动也会有关系。今天尝试新的方法经测试有效,贡献出来:
private double MeasureTextWidth(string text, double fontSize, string fontFamily)
{
FormattedText formattedText = new FormattedText(
text,
System.Globalization.CultureInfo.InvariantCulture,
FlowDirection.LeftToRight,
new Typeface(fontFamily.ToString()),
fontSize,
Brushes.Black
);
return formattedText.WidthIncludingTrailingWhitespace;
}
另,附送枚举已安装字体的方法:
System.Drawing.FontFamily[] fontFamilies;
InstalledFontCollection installedFontCollection = new InstalledFontCollection();
fontFamilies = installedFontCollection.Families;
int count = fontFamilies.Length;
log("fontFamilies.Length=" + fontFamilies.Length);
for (int i = 0; i < count; i++)
{
fontName = fontFamilies[i].Name;
log("fontName: " + fontName);
}
参考自:http://zwkufo.blog.163.com/blog/static/258825120116663748213/