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
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 thatCGContextShowGlyphs
does not do.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With