Convert UIFont to CTFontRef and add italic on Retina display

Dalzhim picture Dalzhim · Mar 19, 2012 · Viewed 10.2k times · Source

I have a custom subclass of UILabel which makes custom drawing using CoreText. I used to draw my strings using the UIFont that is set on the label accessing it using the font property. I also add some traits to the font. Here is what it looks like:

UIFont* font = [self font];
CTFontRef ref = CTFontCreateWithName((CFStringRef)[font name], [font pointSize], NULL);
CTFontRef italicFont = CTFontCreateCopyWithSymbolicTraits(ref, [font pointSize], NULL, kCTFontItalicTrait, kCTFontItalicTrait);

This used to work fine until the new ipad appeared with its retina display. When I perform the CTFontCreateCopyWithSymbolicTraits call, it produces a nil return value. I found out [font name] returns ".HelveticaNeueUI" on these new devices. The CTFontCreateWithName seems to work fine with this private font name, but CTFontCreateCopyWithSymbolicTraits doesn't. Yet if I create an italic font using [UIFont italicSystemFontOfSize:[font pointSize]] it creates an italic font for which [font name] still returns ".HelveticaNeueUI".

How should I convert my UIFont to CTFontRef so that I can still apply new traits to my CTFontRef on both retina and non-retina displays?

Answer

unexpectedvalue picture unexpectedvalue · May 16, 2012

A bit old but for whomever it might still concern:

That happens because the new Neue Helvetica system font used in new retina devices (iPhone 4, iPad) doesn't have an italic version. Not every font has a bold and/or italic variant.
So, if you need italic text, you need to use a different font, for example, the old Helvetica.

CTFontRef ref = CTFontCreateWithName((CFStringRef)@"Helvetica", 12, NULL);
CTFontRef italicFont = CTFontCreateCopyWithSymbolicTraits(ref, 12, NULL, kCTFontItalicTrait, kCTFontItalicTrait);