4

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

ここに画像の説明を入力

4

1 に答える 1

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 の結果は次のとおりです。

ここに画像の説明を入力

于 2014-05-19T17:40:24.603 に答える