NSString drawInRect:withAttributes:使用NSKernAttributeName时未正确居中

Joh*_*rug 4 core-graphics text-alignment nsstring kerning ios

当我使用drawInRect:withAttributes:并传入段落样式NSTextAlignmentCenter和非零值时NSKernAttributeName,字符串不会正确居中.我做错了什么或这是预期的行为?有解决方法吗?

截图:

在此输入图像描述

您可以清楚地看到顶部文本未正确居中.

我的演示代码:

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    UIFont *font = [UIFont systemFontOfSize:15.0];
    [self drawString:@"88" inRect:rect font:font textColor:[UIColor blackColor]];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextAddRect(context, rect);
    CGContextStrokePath(context);
    CGContextRestoreGState(context);
}

- (void)drawString:(NSString *)text
            inRect:(CGRect)contextRect
              font:(UIFont *)font
         textColor:(UIColor *)textColor
{
    CGFloat fontHeight = font.lineHeight;
    CGFloat yOffset = floorf((contextRect.size.height - fontHeight) / 2.0) + contextRect.origin.y;

    CGRect textRect = CGRectMake(contextRect.origin.x, yOffset, contextRect.size.width, fontHeight);

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByClipping;
    paragraphStyle.alignment = NSTextAlignmentCenter;

    [text drawInRect:textRect withAttributes:@{NSKernAttributeName: @(self.kerning),
                                            NSForegroundColorAttributeName: textColor,
                                            NSFontAttributeName: font,
                                            NSParagraphStyleAttributeName: paragraphStyle}];
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

更新,感谢此评论,我添加NSBackgroundColorAttributeName: [UIColor greenColor]了属性并得到以下结果:

在此输入图像描述

Mar*_*n R 13

字距调整必须仅应用于每个字距调整对的第一个字符.如果要显示所有n字符之间都有字距调整的字符串,则必须为第一个n-1字符设置字距调整属性.

代替:

[text drawInRect:textRect withAttributes:@{NSKernAttributeName: @(self.kerning),
                                        NSForegroundColorAttributeName: textColor,
                                        NSFontAttributeName: font,
                                        NSParagraphStyleAttributeName: paragraphStyle}];
Run Code Online (Sandbox Code Playgroud)

您必须创建一个属性字符串,以便您可以为特定范围而不是整个字符串设置字距调整属性:

NSMutableAttributedString *as = [[NSMutableAttributedString alloc]
                                 initWithString:text
                                 attributes:@{
                                              NSForegroundColorAttributeName: textColor,
                                              NSFontAttributeName: font,
                                              NSParagraphStyleAttributeName: paragraphStyle}];
[as addAttribute:NSKernAttributeName
           value:@(self.kerning)
           range:NSMakeRange(0, [text length] - 1)];

[as drawInRect:textRect];
Run Code Online (Sandbox Code Playgroud)

这里是字符串"1234"和字距-4.0的结果:

在此输入图像描述