使用Core Text的多语言布局中的行间距

an0*_*an0 9 core-text ios

属性字符串只有一个属性 - 17点Helvetica NeueUI字体 - 覆盖整个字符串.1~3行纯英语,4~6行是英汉混合,7~8行纯粹是中文.

然后使用CTFramesetter进行布局,并使用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);
}
Run Code Online (Sandbox Code Playgroud)

问题是7号线和8号线(纯粹的中国线)之间的空间比其他线要小得多.

相比之下,我UILabel在它下面放了一个字体和文字.忽略单个字符的渲染差异,您可以看到行间距UILabel是均匀的,包括两个中文行之间的最后一行.

截图

注意:上面的结果是在真实设备上获得的.如果在模拟器上运行相同的代码,Core Text视图的结果会有很大差异 - 包含中文的行之间的空间比其他行大得多.

  1. 为什么中国线之间的空间更小(更大)?
  2. 如何使用Core Text布置具有统一线高的多语言文本?

PS:这是您可以自己尝试的示例项目.

an0*_*an0 1

终于得到了苹果工程师的官方答复:

CTLine 指标基于 {ascent、descent、leading} 中每个值的最大值;这一点没有改变,也不会改变。客户端可以使用段落样式说明符或 iOS 7 文本样式覆盖行规格,例如 [UIFont PreferredFontForTextStyle:UIFontTextStyleBody]。