Alex Rivera | Logout

Is it possible to alter the letter-spacing/kerning of a font with Cocoa Touch?

Asked 2009-06-30T11:58:10.703
15

I've been scouring the Internet for a while now for information on how one can alter the letter-spacing/kerning of a font within UIKit.

My fear is, that like using your own custom fonts, you simply can't. Which would be terrible news.

I know Apple is protecting us from bad design with these constraints, but they're also preventing us from implementing really great design too.

What do people suggest I do?

  1. Use the font with the standard kerning, people probably wouldn't notice the difference anyway.

  2. Find someone's hacked class to get the look the user deserves after parting with their hard earned cash.

  3. Use the method that I've somehow overlooked, and do it with UIKit, pledging my eternal gratitude to the person who imparts this hidden nugget of knowledge.

Edit
Report

1 Answer

1

The main problem of CGContextShowText methods - they are diaplays only ASCII strings. To display UTF strings you need to map your string symbols to glyphs and show glyphs.

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSelectFont (context, [self.font.fontName cStringUsingEncoding:NSASCIIStringEncoding], self.font.pointSize, kCGEncodingMacRoman);
    CGContextSetCharacterSpacing(context, characterSpacing);
    CGContextSetFillColorWithColor(context, [self.textColor CGColor]);
    CGAffineTransform myTextTransform = CGAffineTransformScale(CGAffineTransformIdentity, 1.f, -1.f );
    CGContextSetTextMatrix (context, myTextTransform);

    CGGlyph glyphs[self.text.length];
    CTFontRef fontRef = CTFontCreateWithName((CFStringRef)self.font.fontName, self.font.pointSize, NULL);
    CTFontGetGlyphsForCharacters(fontRef, (const unichar*)[self.text cStringUsingEncoding:NSUnicodeStringEncoding], glyphs, self.text.length);
    float centeredY = (self.font.pointSize + (self.frame.size.height- self.font.pointSize)/2)-2;
    CGContextShowGlyphsAtPoint(context, rect.origin.x, centeredY, (const CGGlyph *)glyphs, self.text.length);
answered 2012-08-22T09:42:31.647

Your Answer