Convert UIFont to CTFontRef and add italic on Retina display
Asked Answered
N

3

9

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?

Nihon answered 19/3, 2012 at 16:59 Comment(0)
S
14

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);
Slaby answered 16/5, 2012 at 14:28 Comment(1)
Ha. Welcome to Core Text.Yiyid
T
3

Converting UIFont/NSFont to CTFontRef is very simple if you use ARC.

UIFont:

UIFont *uiFont = [UIFont fontWithName:@"Helvetica" size:10];
CTFontRef ctFont = (__bridge CTFontRef)uiFont;

NSFont:

NSFont *nsFont = [NSFont fontWithName:@"Helvetica" size:10];
CTFontRef ctFont = (__bridge CTFontRef)nsFont;
Tambratamburlaine answered 4/5, 2017 at 10:33 Comment(0)
T
0

use this way,convert uifont to CTFontRef

UIFont *uiFont = [UIFont fontWithName:@"Helvetica" size:10];
CTFontRef ctFont = (__bridge CTFontRef)uiFont;

Do we need release the ctFont

Turmel answered 12/6, 2020 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.