如何使用CTFontRef获取FontFormat

时间:2011-08-23 13:36:56

标签: objective-c cocoa macos deprecated macos-carbon

使用FMGetFontFormat的旧碳代码确定Font是否为“True Type”。由于不推荐使用API​​,有没有办法使用CTFontRef查找相同的API。我使用CTFontCopyAttribute,但是它返回CTTypeRef并且我无法获得该值?有什么建议吗?

1 个答案:

答案 0 :(得分:4)

CTTypeRef是通用类型。如果您阅读kCTFontFormatAttribute常量的文档,则说明:

  

与此键关联的值是表示为a的整数   CFNumberRef对象包含“字体格式”中的一个常量   常量“。

这意味着您需要将该属性视为一个数字,然后您可以将其转换为short并根据CTFontFormat的已知值进行检查:

//get an array of all the available font names
CFArrayRef fontFamilies = CTFontManagerCopyAvailableFontFamilyNames();

//loop through the array
for(CFIndex i = 0; i < CFArrayGetCount(fontFamilies); i++)
{
    //get the current name
    CFStringRef fontName = CFArrayGetValueAtIndex(fontFamilies, i);

    //create a CTFont with the current font name
    CTFontRef font = CTFontCreateWithName(fontName, 12.0, NULL);

    //ask it for its font format attribute
    CFNumberRef fontFormat = CTFontCopyAttribute(font, kCTFontFormatAttribute);

    //release the font because we're done with it
    CFRelease(font);

    //if there is no format attribute just skip this one
    if(fontFormat == NULL)
    {
        NSLog(@"Could not determine the font format for font named %@.", fontName);
        continue;
    }

    //get the font format as a short
    SInt16 format;
    CFNumberGetValue(fontFormat, kCFNumberSInt16Type, &format);

    //release the number because we're done with it
    CFRelease(fontFormat);

    //create a human-readable string based on the format of the font
    NSString* formatName = nil;
    switch (format) {
        case kCTFontFormatOpenTypePostScript:
            formatName = @"OpenType PostScript";
            break;
        case kCTFontFormatOpenTypeTrueType:
            formatName = @"OpenType TrueType";
            break;
        case kCTFontFormatTrueType:
            formatName = @"TrueType";
            break;
        case kCTFontFormatPostScript:
            formatName = @"PostScript";
            break;
        case kCTFontFormatBitmap:
            formatName = @"Bitmap";
            break;
        case kCTFontFormatUnrecognized:
        default:
            formatName = @"Unrecognized";
            break;
    }
    NSLog(@"Font: '%@' Format: '%@'", fontName, formatName);
}