UILabel with a (custom) CGFont

Thu, 26. Aug 2010

Categories: en development Tags: CGFont Cocoa iOS iPhone Objective C OTF TrueType TTF UIFont UILabel

UILabel’s font property accepts UIFonts – but strange enough there’s no way to get a custom loaded CGFont (from a ttf or otf file)Β converted into such an UIFont. You’re stuck with the iPhone’s pre-installed fonts – at least when you have to support iOS 3.0 devices.

After googling a bit and searching Stackoverflow I found the solutions presented there not ideal or great, but too heavy weight.

So I inherited UILabel with a very lean custom class UILabelWithCGFont and overloaded it’s drawTextInRect: method like this:

 1-(void)drawTextInRect:(CGRect)rect
 2{
 3  MRLogD(@"(%f,%f) (%f,%f)", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
 4  if ( _CGFont == NULL ) {
 5    [super drawTextInRect:rect];
 6    return;
 7  }
 8  NSAssert(_mapping != NULL, @"Mapping function pointer not set.");
 9
10  // prepare the target graphics context.
11  const CGContextRef ctx = UIGraphicsGetCurrentContext();
12  CGContextSaveGState(ctx);
13  {
14    // prepare the glyphs array to draw
15    const NSString *txt = self.text;
16    const size_t glyphCount = txt.length;
17    CGGlyph glyphs[glyphCount];
18    {
19      // turn the string txt into glyphs (indices into the font):
20      // give non-allocating unicode character retrieval a try:
21      const UniChar *raw_unichars = CFStringGetCharactersPtr( (CFStringRef)txt );
22      const UniChar *unichars = raw_unichars == NULL ? malloc( glyphCount * sizeof(UniChar) ) : raw_unichars;
23      NSAssert(unichars != NULL, @"unichars not allocated");
24      if ( raw_unichars == NULL )
25        CFStringGetCharacters( (CFStringRef)txt, CFRangeMake(0, txt.length), (UniChar *)unichars );
26      for ( int i = glyphCount - 1; i >= 0; i-- )
27        glyphs[i] = _mapping(unichars[i]);
28      if ( raw_unichars == NULL )
29        free( (void *)unichars );
30    }
31
32    CGContextSetFont(ctx, _CGFont);
33    CGContextSetFontSize(ctx, self.font.pointSize);
34    CGContextSetTextMatrix( ctx, CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0) );
35
36    // first print 'invisible' to measure size:
37    CGContextSetTextDrawingMode(ctx, kCGTextInvisible);
38    const CGPoint pre = CGContextGetTextPosition(ctx);
39    CGContextShowGlyphs(ctx, glyphs, glyphCount);
40    const CGPoint post = CGContextGetTextPosition(ctx);
41    // restore text position
42    CGContextSetTextPosition(ctx, pre.x, pre.y);
43
44    // centered horizontal + vertical:
45    NSAssert( (int)rect.origin.x == 0, @"origin.x not zero" );
46    NSAssert( (int)rect.origin.y == 0, @"origin.y not zero" );
47    NSAssert(self.baselineAdjustment == UIBaselineAdjustmentAlignCenters, @"vertical alignment not 'center'");
48    NSAssert(self.textAlignment == UITextAlignmentCenter, @"horizontal alignment not 'center'");
49    const CGPoint p = CGPointMake( ( rect.size.width - (post.x - pre.x) ) / 2, (rect.size.height + self.font.pointSize + pre.y) / 2 );
50
51    // finally render it to the graphics context:
52    CGContextSetTextDrawingMode(ctx, kCGTextFill);
53    CGContextSetFillColorWithColor(ctx, self.textColor.CGColor);
54    CGContextShowGlyphsAtPoint(ctx, p.x, p.y, glyphs, glyphCount);
55  }
56  CGContextRestoreGState(ctx);
57}

Usage: Just turn the UILabel instances in Interface Builder into UILabelWithCGFont and implement the UIViewController::viewDidLoad method like this:

 1CGGlyph unicode2glyphDeutscheDruckschrift(UniChar c)
 2{
 3  if ( '0' < = c && c <= '9' )
 4    return c + (16 - '0');
 5  if ( 'A' <= c && c <= 'Z' )
 6    return c + (32 - 'A');
 7  if ( 'a' <= c && c <= 'z' )
 8    return c + (58 - 'a');
 9  return 0;
10}
11
12-(void)viewDidLoad
13{
14  [super viewDidLoad];
15  ...
16  [fontLabel setFontFromFile:@"DeutscheDruckschrift" ofType:@"ttf" mapping:unicode2glyphDeutscheDruckschrift];
17  ...
18}

See this github gist for the complete implementation.

The mapping from Unicode character codes to glyph indices (inside the font description) currently is done via a C mapping function you have to provide a function pointer for. A later implementation could map the unicode character code to the glyph name and leverage Β CGFontGetGlyphWithGlyphName and render the custom mapping function obsolete.