是否可以使用 C#、C++/CLI 或通过 P/调用 WinAPI 来确定某个字体系列是否为 TrueType 字体?
最后我希望得到这样的结果
bool result1 = CheckIfIsTrueType(new FontFamily("Consolas")); //returns true
bool result2 = CheckIfIsTrueType(new FontFamily("Arial")); // returns true
bool result3 = CheckIfIsTrueType(new FontFamily("PseudoSaudi")); // returns false
bool result4 = CheckIfIsTrueType(new FontFamily("Ubuntu")); // returns true
bool result5 = CheckIfIsTrueType(new FontFamily("Purista")); // returns false
当然,结果取决于目标操作系统及其字体......
最佳答案
它有处理异常的开销,但是FontFamily
constructor如果提供的字体不是 TrueType,则抛出 ArgumentException
:
public bool CheckIfIsTrueType(string font)
{
try
{
var ff = new FontFamily(font)
}
catch(ArgumentException ae)
{
// this is also thrown if a font is not found
if(ae.Message.Contains("TrueType"))
return false;
throw;
}
return true;
}
深入研究 FontFamily 构造函数,它调用外部 GDIPlus 函数 GdipCreateFontFamilyFromName
:
[DllImport("Gdiplus", SetLastError=true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
internal static extern int GdipCreateFontFamilyFromName(string name, HandleRef fontCollection, out IntPtr FontFamily);
如果字体不是 true type 字体,则返回代码 16
。因此您可以绕过异常的开销:
public bool CheckIfIsTrueType(string name)
{
IntPtr fontfamily = IntPtr.Zero;
IntPtr nativeFontCollection = IntPtr.Zero ;
int status = GdipCreateFontFamilyFromName(name, new HandleRef(null, nativeFontCollection), out fontfamily);
if(status != 0)
if(status == 16) // not true type font)
return false;
else
throw new ArgumentException("GDI Error occurred creating Font");
return true;
}
显然,您可能想在代码中使用常量枚举,可以在 here 中找到。 ,并抛出更好的异常
关于c# - 检查 FontFamily 是否为 TrueType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32528726/