是否可以使用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当然,结果取决于目标操作系统及其字体.
发布于 2015-09-11 17:38:56
它具有处理异常的开销,但如果所提供的字体不是构造函数,则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);如果字体不是真正类型的字体,则返回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;
}显然,您可能希望对代码使用常量枚举(可以找到这里 ),并抛出更好的异常。
发布于 2019-01-23 19:53:30
如果目标操作系统是Windows 10,则不会出现执行D Stanley的C#示例代码的异常。仅在windows 7上引发异常。GDI+在windows 8和Windows 10上支持使用Adobe大纲的OTF字体。
https://stackoverflow.com/questions/32528726
复制相似问题