开发者

How to get FontFormat using CTFontRef

There is old carbon code using FMGetFontFormat to determine if the Font is of "Tr开发者_运维百科ue Type". Since the API is deprecated, is there a way to find the same using CTFontRef. I used CTFontCopyAttribute, but it is returning CTTypeRef and i am not able to get the value? Any Suggestions?


A CTTypeRef is a generic type. If you read the docs for the kCTFontFormatAttribute constant, they state:

The value associated with this key is an integer represented as a CFNumberRef object containing one of the constants in “Font Format Constants.”

That means that you need to treat the attribute as a number, which you can then convert to a short and check it against the known values for 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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜