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]
したところ、次の結果が得られました。