gpt4 book ai didi

ios - NSString 绘制矩形 :withAttributes: not correctly centered when using NSKernAttributeName

转载 作者:可可西里 更新时间:2023-11-01 05:03:16 27 4
gpt4 key购买 nike

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

截图:

enter image description here

您可以清楚地看到顶部文本没有正确居中。

我的演示代码:

- (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] 添加到属性中并得到以下结果:

enter image description here

最佳答案

紧缩只能应用于每个紧缩对的第一个 字符。如果要在所有 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 的结果:

enter image description here

关于ios - NSString 绘制矩形 :withAttributes: not correctly centered when using NSKernAttributeName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23741850/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com