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.
Asked
Active
Viewed 6,516 times
4 Answers
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);

JOM
- 8,139
- 6
- 78
- 111

Rob Keniger
- 45,830
- 6
- 101
- 134
-
This doesn't work under Snow Leopard (confirmed by Apple) and you need to use `ATSFontActivateFromMemory()` on that version of OS X only. – trojanfoe Jul 20 '12 at 08:25
-
Cannot confirm this. It works fine here on Snow Leopard. – Andreas Aug 30 '16 at 14:21
-
This seems to be missing the size, matrix, and attributes arguments to CTFontCreateWithGraphicsFont() – David Jones Apr 19 '22 at 15:54
11
It looks like CTFontManagerCreateFontDescriptorsFromURL
is the Core Text replacement.
-
2And it makes for [shorter code than the Core Graphics route](https://gist.github.com/1696100). – Peter Hosey Jan 28 '12 at 22:57
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)

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

Muruganandham K
- 5,271
- 5
- 34
- 62