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

前端 未结 4 1503
暖寄归人
暖寄归人 2020-12-24 10:18

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

相关标签:
4条回答
  • 2020-12-24 10:36
    NSURL *fontURL = [[NSBundle mainBundle] URLForResource:@"Crystal" withExtension:@"ttf"];
        assert(fontURL);
        CFErrorRef error = NULL;
        if (!CTFontManagerRegisterFontsForURL((__bridge CFURLRef)fontURL, kCTFontManagerScopeProcess, &error))
        {
            CFShow(error);
            abort();
        }
    
    0 讨论(0)
  • 2020-12-24 10:46

    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);   
    
    0 讨论(0)
  • It looks like CTFontManagerCreateFontDescriptorsFromURL is the Core Text replacement.

    0 讨论(0)
  • 2020-12-24 10:52

    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)
    
    0 讨论(0)
提交回复
热议问题