当我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}];
}
谢谢!
更新,感谢这条评论,我添加NSBackgroundColorAttributeName: [UIColor greenColor]
了属性并得到以下结果: