如何使用“核心文字”从文件中加载字体(TTF)?

问题描述 投票:13回答:4

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

cocoa macos macos-carbon osx-snow-leopard core-text
4个回答
19
投票

您可以通过CTFontRef从字体文件中获得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);   

10
投票

CTFontManagerCreateFontDescriptorsFromURL似乎是Core Text的替代品。


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

0
投票

这里是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)
© www.soinside.com 2019 - 2024. All rights reserved.