首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查FontFamily是否为TrueType

检查FontFamily是否为TrueType
EN

Stack Overflow用户
提问于 2015-09-11 17:08:44
回答 2查看 1.8K关注 0票数 2

是否可以使用C#、C++/CLI或P/调用WinAPI来确定某个字体家族是TrueType字体?

最后,我希望得到这样的结果

代码语言:javascript
复制
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

当然,结果取决于目标操作系统及其字体.

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-11 17:38:56

它具有处理异常的开销,但如果所提供的字体不是构造函数,则ArgumentException抛出:

代码语言:javascript
复制
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

代码语言:javascript
复制
[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代码。因此,您可以绕过异常的开销:

代码语言:javascript
复制
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;
}

显然,您可能希望对代码使用常量枚举(可以找到这里 ),并抛出更好的异常。

票数 3
EN

Stack Overflow用户

发布于 2019-01-23 19:53:30

如果目标操作系统是Windows 10,则不会出现执行D Stanley的C#示例代码的异常。仅在windows 7上引发异常。GDI+在windows 8和Windows 10上支持使用Adobe大纲的OTF字体。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32528726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档