objective-cmacoscocoansfont

Custom fonts in Objective-C Application


This question isn't really asking what you might think on the surface. I already know how to use custom fonts in objective-c applications. The question is more in regards to the specifics about using custom fonts, mainly — If I use a custom font that suppose someone else may not have on their machine will it still render it properly? I haven't seen anything in pertaining to whether or not that becomes a factor if someone doesn't have the same typeface.

Also, is there any connection with my question and the object within interface builder? thanks.

enter image description here


Solution

  • Custom fonts only work if your users have them too. Otherwise, the font needs to be bundled with your program and loaded in a way similar to this one. Always make sure that you are allowed to distribute the font with your program.

    -(NSFont*)fontWithName:(NSString*)name height:(CGFloat)height
    {
        NSURL* fontURL = [NSBundle.mainBundle URLForResource:name withExtension:@"ttf"];
        if (fontURL == nil)
        {
            return nil;
        }
    
        CGDataProviderRef dataProvider = CGDataProviderCreateWithURL((CFURLRef)fontURL);
        if (dataProvider == NULL)
        {
            return nil;
        }
    
        CTFontRef coreTextFont = NULL;
        CGFontRef font = CGFontCreateWithDataProvider(dataProvider);
        if (font != NULL)
        {
            coreTextFont = CTFontCreateWithGraphicsFont(font, height, NULL, NULL);
        }
    
        CGDataProviderRelease(dataProvider);
        CGFontRelease(font);
        return CFBridgingRelease(coreTextFont);
    }