How can you load a font (TTF) from a file using Core Text?
Asked Answered
M

4

17

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.

Madge answered 24/4, 2010 at 3:20 Comment(0)
M
20

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);   
Mcmorris answered 24/4, 2010 at 4:16 Comment(3)
This doesn't work under Snow Leopard (confirmed by Apple) and you need to use ATSFontActivateFromMemory() on that version of OS X only.Columbine
Cannot confirm this. It works fine here on Snow Leopard.Legator
This seems to be missing the size, matrix, and attributes arguments to CTFontCreateWithGraphicsFont()Laylalayman
M
11

It looks like CTFontManagerCreateFontDescriptorsFromURL is the Core Text replacement.

Madge answered 24/4, 2010 at 3:37 Comment(1)
And it makes for shorter code than the Core Graphics route.Pigtail
C
6

Here's an updated version of how to do this in 2020. Much simpler now. Used 12 as arbitrary type size.

let fontURL = URL(fileURLWithPath: "path/to/font.otf")
let fd = CTFontManagerCreateFontDescriptorsFromURL(fontURL as CFURL) as! [CTFontDescriptor]
let theCTFont = CTFontCreateWithFontDescriptor(fd[0], 12.0, nil)
Colophon answered 2/2, 2020 at 22:34 Comment(0)
B
5
NSURL *fontURL = [[NSBundle mainBundle] URLForResource:@"Crystal" withExtension:@"ttf"];
    assert(fontURL);
    CFErrorRef error = NULL;
    if (!CTFontManagerRegisterFontsForURL((__bridge CFURLRef)fontURL, kCTFontManagerScopeProcess, &error))
    {
        CFShow(error);
        abort();
    }
Bezant answered 10/7, 2013 at 8:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.