Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing Unicode characters on iPhone

Why is it so hard to figure out how to draw Unicode characters on the iPhone, deriving simple font metrics along the way, such as how wide each imaged glyph is going to be in the font of choice?

It looks like it'd be easy with NSLayoutManager, but that API apparently isn't available on the phone. It appears the way people are doing this is to use a private API, CGFontGetGlyphsForUnichars, which won't get you past the Apple gatekeepers into the App store.

Can anybody point me to documentation that shows how to do this? I'm losing hair rapidly.

Howard

like image 883
hkatz Avatar asked May 25 '09 13:05

hkatz


2 Answers

I assumed that the exclusion of CGFontGetGlyphsForUnichars
was an oversight rather than a deliberate move, however I'm not
betting the farm on it. So instead I use

[NSString drawAtPoint:withFont:]; (in UIStringDrawing.h)

and

[NSString sizeWithFont];

This also has the advantage of performing decent substitution
on characters missing from your font, something that
CGContextShowGlyphs does not do.

like image 187
Rhythmic Fistman Avatar answered Sep 30 '22 20:09

Rhythmic Fistman


CoreText is the answer if you want to draw unicode rather than CGContextShowGlyphsAtPositions. Also it's better than [NSString drawAtPoint:withFont:] if you need custom drawing. Here is a complete example:

CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)attributedString);
CFArrayRef runArray = CTLineGetGlyphRuns(line);

//in more complicated cases make loop on runArray
//here I assumed this array has only 1 CTRunRef within
const CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runArray, 0);

//do not use CTFontCreateWithName, otherwise you won't see e.g. chinese characters
const CTFontRef font = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);

CFIndex glyphCount = CTRunGetGlyphCount(run);
CGGlyph glyphs[glyphCount];
CGPoint glyphPositions[glyphCount];

CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs);
//you can modify positions further
CTRunGetPositions(run, CFRangeMake(0, 0), glyphPositions);

CTFontDrawGlyphs(font, glyphs, glyphPositions, glyphCount, context);
CFRelease(line);
like image 38
icywire Avatar answered Sep 30 '22 18:09

icywire