How can you load a font (TTF) from a file using Co

2019-02-01 01:53发布

问题:

Prior to OSX 10.6, ATSFontActivateFromFileSpecification/ATSFontActivateFromFileReference were available and could be used to load a font from a file. I can't find anything similar in Core Text.

回答1:

You can get a CTFontRef from a font file by going via a CGFontRef:

CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, CFSTR("/path/to/font"), kCFURLPOSIXPathStyle, false);
CGDataProviderRef dataProvider = CGDataProviderCreateWithURL(url);
CGFontRef theCGFont = CGFontCreateWithDataProvider(dataProvider);
CTFontRef theCTFont = CTFontCreateWithGraphicsFont(theCGFont);
CFRelease(theCGFont);
CFRelease(dataProvider);
CFRelease(url);

// do something with the CTFontRef here

CFRelease(theCTFont);   


回答2:

It looks like CTFontManagerCreateFontDescriptorsFromURL is the Core Text replacement.



回答3:

NSURL *fontURL = [[NSBundle mainBundle] URLForResource:@"Crystal" withExtension:@"ttf"];
    assert(fontURL);
    CFErrorRef error = NULL;
    if (!CTFontManagerRegisterFontsForURL((__bridge CFURLRef)fontURL, kCTFontManagerScopeProcess, &error))
    {
        CFShow(error);
        abort();
    }