为什么System.Drawing.Fontconverter.ConvertFromInvariantString(“NOTAFONT”)返回SansSerif?

时间:2014-07-15 04:51:08

标签: c# serialization fonts

为什么

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"尺寸= 1.2}

2 个答案:

答案 0 :(得分:3)

MSDN Documentation on the Font Class下查看备注部分有一个有趣的陈述。

即:

  

有关如何构造字体的详细信息,请参见如何:构造字体系列和字体。 Windows窗体应用程序支持TrueType字体,并且对OpenType字体的支持有限。 如果您尝试使用不受支持的字体,或者在运行该应用程序的计算机上未安装该字体,则Microsoft Sans Serif字体将被替换

我认为你看到了这种行为。

不确定这是否符合您的需求,但在这种情况下,我使用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));
}

答案 1 :(得分:1)

如果找不到给定的字体并且不可用,您似乎总是得到“Microsoft Sans Serif”字体。我用FontConverter类和Font类试了一下。

我用

尝试了
var font = new Font("Arial", 12, FontStyle.Bold);

并获得指定的Arial字体。

我在MSDN上找不到关于这个主题的任何评论,如果找不到给定的字体,总会返回“Microsoft Sans Serif”。​​