Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert CGFontRef to UIFont?

I want to use a custom font for a UILabel. The custom font is loaded by from a file:

NSString *fontPath = ... ; // a TTF file in iPhone Documents folder
CGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fontPath UTF8String]);
CGFontRef customFont = CGFontCreateWithDataProvider(fontDataProvider);
CGDataProviderRelease(fontDataProvider); 

How can I convert the CGFontRef to a UIFont to be used in [UILabel setFont:]?

like image 389
ohho Avatar asked Feb 09 '12 05:02

ohho


2 Answers

You can't convert CGFontRef to UIFont directly but you can register CGFontRef using CTFontManagerRegisterGraphicsFont and then create corresponding UIFont.

NSString* fpath = [documentsDirectory stringByAppendingPathComponent:@"custom_font_file_name.ttf"];
CGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fpath UTF8String]);
CGFontRef customFont = CGFontCreateWithDataProvider(fontDataProvider);
CGDataProviderRelease(fontDataProvider);
NSString *fontName = (__bridge NSString *)CGFontCopyFullName(customFont);
CFErrorRef error;
CTFontManagerRegisterGraphicsFont(customFont, &error);
CGFontRelease(customFont);
UIFont* uifont = [UIFont fontWithName:fontName size:12];
like image 138
Pavel Konovalov Avatar answered Oct 11 '22 14:10

Pavel Konovalov


Conrad's answer is close but doesn't quite work. You need to provide UIFont with the PostScript name, rather than the full name.

NSString *fontName = (NSString *)CGFontCopyPostScriptName(fontRef);
UIFont *font = [UIFont fontWithName:fontName size:someSize]
like image 40
Josh Brown Avatar answered Oct 11 '22 14:10

Josh Brown