为什么在iPhone上绘制Unicode字符很难,期间还要推导出简单的字体度量值,例如所选字体中每个图像字形的宽度?看起来使用NSLayoutManager会很容易,但是这个API似乎在手机上不可用。目前人们似乎是使用私有API CGFontGetGlyphsForUnichars 来实现,但这样做无法通过Apple的应用商店审核门槛。请问是否有人能提供相应的文档说明如何解决这个问题呢?我快要秃头了。
Howard
Howard
CGFontGetGlyphsForUnichars
是一个疏忽而不是故意的举动,但我并不确定。因此,我使用[NSString drawAtPoint:withFont:]
(在UIStringDrawing.h中)和[NSString sizeWithFont]
。这样做的优点是,它可以对字体中缺失的字符进行良好的替换,而CGContextShowGlyphs
则不能做到这一点。如果您想要绘制Unicode而不是使用CGContextShowGlyphsAtPositions
,那么CoreText就是您的答案。此外,如果需要自定义绘图,则它比[NSString drawAtPoint:withFont:]
更好。
以下是一个完整的示例:
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);
UIGraphicsGetCurrentContext
),并在绘制前后使用CGContextGetTextPosition
来获取边界框的宽度。这基本上是我感兴趣的主要内容,所以谢谢! - hkatz[@"a" sizeWithFont:<font>]
有什么问题吗? 为什么需要单个字符的度量? - Andrew Pouliot