Custom font in a Cocoa application

前端 未结 4 1111
渐次进展
渐次进展 2020-12-08 01:23

I know you can customize fonts by using Interface Builder and selecting a font. However, I\'m curious if I can use a custom font that\'s not included by default on systems.

4条回答
  •  既然无缘
    2020-12-08 01:56

    ATSApplicationFontsPath uses [NSBundle mainbundle] path as base path, so it does not work when Resources folder is not located there (e.g. for app plugins).

    In my Cocoa plugin I need to load custom fonts using CTFontManagerRegisterFontsForURL

    #import 
    
    static void FGDActivateFont(NSString *fontName)
    {
    
        // Can't make ATSApplicationFontsPath in Info.plist work for plugins (non-standard Resources path)
    
        NSArray *availableFonts = [[NSFontManager sharedFontManager] availableFonts];
    
        if (![availableFonts containsObject:fontName]) {
    
            NSURL *fontURL = [[FGDRapidCart bundle] URLForResource:fontName withExtension:@"ttf" subdirectory:@"Fonts"];
            assert(fontURL);
            CFErrorRef error = NULL;
            if (!CTFontManagerRegisterFontsForURL((__bridge CFURLRef)fontURL, kCTFontManagerScopeProcess, &error))
            {
                CFShow(error);
            }
    
        }
    
    }
    
    int main(int argc, char *argv[])
    {
        @autoreleasepool
        {
            FGDActivateFont(@“FontAwesome”);
        }
        return NSApplicationMain(argc, (const char **)argv);
    }
    

    Credits: https://github.com/OneSadCookie/Extendaword/blob/master/Extendaword/main.m

提交回复
热议问题