的屬性串只有一個屬性的多語言佈局 - 17點Helvetica字體NeueUI - 覆蓋整個字符串。 1〜3行純英文,4〜6行是英文和中文混合,7〜8行純中文。行距與核心文本
然後將其用CTFramesetter和所得幀layouted畫有CTFrameDraw。
// UIView subclass
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor whiteColor];
CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica NeueUI"), 17.f, NULL);
_text = [[NSAttributedString alloc] initWithString:string attributes:
[NSDictionary dictionaryWithObject:(id)font forKey:(id)kCTFontAttributeName]];
CFRelease(font);
_framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)_text);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, self.bounds);
_frame = CTFramesetterCreateFrame(_framesetter, CFRangeMake(0, 0), path, NULL);
CGPathRelease(path);
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
// Flip the coordinate system.
CGContextTranslateCTM(context, 0.f, self.bounds.size.height);
CGContextScaleCTM(context, 1.f, -1.f);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CTFrameDraw(_frame, context);
CGContextRestoreGState(context);
}
問題是第7行和第8行之間的空格(純中文行)比其他行小得多。
爲了便於比較,我把UILabel
下方,用同樣的字體和文字。忽略單個字符的渲染差異,可以看到UILabel
中的行空格是統一的,包括兩個中文行之間的最後一行。
注意:這上面的結果是得到了一個真正的設備上。如果你在模擬器上運行相同的代碼,核心文本視圖會得到非常不同的結果 - 包含中文的行之間的空間比其他空間大得多。
- 爲什麼中國線之間的距離較小(較大)?
- 如何使用核心文本來佈置具有統一線高度的多語言文本?
PS:這裏是sample project你可以嘗試自己。
如果您不介意,我很樂意在開發人員論壇上看到您的iOS 5答案(直到您可以在此發佈)。 – 2011-09-26 02:03:40
等待OP交付。 – mxcl 2011-12-20 00:31:03