为什么
var fontConverter = new FontConverter();
var retFont = fontConverter.ConvertFromInvariantString("NOTAFONT");
return {Name = "Microsoft Sans Serif" Size=8.25}
并且不抛出异常?
使用这段代码,我打算测试一个字符串是否包含有效的字体序列化。还有其他方法可以检查吗?
我检查了 FontConverter 类的代码,它创建了这样的 returnfont:
var retFont = new Font("notafont", 1.2f, FontStyle.Bold);
返回的字体是{Name = "Microsoft Sans Serif"Size=1.2}
请您参考如下方法:
在MSDN Documentation on the Font Class下看备注部分有一个有趣的声明。
即:
For more information about how to construct fonts, see How to: Construct Font Families and Fonts. Windows Forms applications support TrueType fonts and have limited support for OpenType fonts. If you attempt to use a font that is not supported, or the font is not installed on the machine that is running the application, the Microsoft Sans Serif font will be substituted.
我认为您看到了这种行为。
不确定这是否能满足您的需求,但在本例中我使用的是 InstalledFontCollection验证字体是否可用。
bool CheckFontAvailability(string value)
{
FontCollection fc = new InstalledFontCollection();
return fc.Families.Any(ff => ff.Name.Contains(value));
}
或由 schoetbi 修改
bool CheckFontAvailability(string fontAsString)
{
FontCollection fc = new InstalledFontCollection();
return fc.Families.Any(ff => fontAsString.StartsWith(ff.Name));
}
