Custom Font

It turned out to be not so trivial to use a custom font. I experimented a lot, and finally reached this solution.

It requires 2 steps:

1. Load the ttf

1
2
3
4
5
6
7
NSString *fontPath = [[NSBundle mainBundle] 
pathForResource:@"#{font_file_name}" ofType:@"ttf"];

CGDataProviderRef fontDataProvider =
CGDataProviderCreateWithFilename([fontPath UTF8String]);

ref = CGFontCreateWithDataProvider(fontDataProvider);

2. Draw glyphs

1
2
3
4
CGContextSetFont(_context, ref);
CGContextSetFontSize(_context, 80);
CGGlyph i = 40;
CGContextShowGlyphsAtPoint(_context, x, y, &i, 1);

It helpers to invert the transformation matrix before drawing, as Apple fucked up the view coordinates in UIKit.

1
2
3
CGRect viewBounds = self.bounds;
CGContextTranslateCTM(_context, 0, viewBounds.size.height);
CGContextScaleCTM(_context, 1, -1);
  • 1.png
blog comments powered by Disqus