Cocoa 如何使用核心文本从文件加载字体(TTF)?

Cocoa 如何使用核心文本从文件加载字体(TTF)?,cocoa,macos,macos-carbon,osx-snow-leopard,core-text,Cocoa,Macos,Macos Carbon,Osx Snow Leopard,Core Text,在OSX 10.6之前,ATSFontActivateFromFileSpecification/ATSFontActivateFromFileReference可用,可用于从文件加载字体。我在核心文本中找不到任何类似的内容。看起来CTFontManagerCreateFontDescriptorsFromURL是核心文本的替代品。您可以通过CGFontRef从字体文件中获得CTFontRef: CFURLRef url = CFURLCreateWithFileSystemPath(kCFAl

在OSX 10.6之前,ATSFontActivateFromFileSpecification/ATSFontActivateFromFileReference可用,可用于从文件加载字体。我在核心文本中找不到任何类似的内容。

看起来
CTFontManagerCreateFontDescriptorsFromURL
是核心文本的替代品。

您可以通过
CGFontRef
从字体文件中获得
CTFontRef

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);   

以下是2020年如何做到这一点的更新版本。现在简单多了。使用12作为任意类型大小

let fontURL = URL(fileURLWithPath: "path/to/font.otf")
let fd = CTFontManagerCreateFontDescriptorsFromURL(fontURL as CFURL) as! [CTFontDescriptor]
let theCTFont = CTFontCreateWithFontDescriptor(fd[0], 12.0, nil)

它有助于。这在雪豹下不起作用(经苹果确认),您需要仅在该版本的OS X上使用
ATSFontActivateFromMemory()
。无法确认。在雪豹身上效果很好。
let fontURL = URL(fileURLWithPath: "path/to/font.otf")
let fd = CTFontManagerCreateFontDescriptorsFromURL(fontURL as CFURL) as! [CTFontDescriptor]
let theCTFont = CTFontCreateWithFontDescriptor(fd[0], 12.0, nil)