当我使用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}];
}
谢谢!
更新,感谢this comment,我在属性中添加了NSBackgroundColorAttributeName: [UIColor greenColor]
并获得了以下结果:
答案 0 :(得分:13)
字距调整必须仅应用于每个字距调整对的第一个字符。
如果要在所有n
个字符之间显示字符串,则需要进行字距调整
必须为第一个n-1
字符设置属性。
而不是:
[text drawInRect:textRect withAttributes:@{NSKernAttributeName: @(self.kerning),
NSForegroundColorAttributeName: textColor,
NSFontAttributeName: font,
NSParagraphStyleAttributeName: paragraphStyle}];
您必须创建一个属性字符串,以便您可以设置字距调整属性 对于特定范围而不是整个字符串:
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];
这里是字符串" 1234"的结果。和字距-4.0: