xcode 如何更改 UILabel/UIFont 的字母间距?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2544905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 03:20:26  来源:igfitidea点击:

How to change an UILabel/UIFont's letter spacing?

iphonexcodeuilabelspacinguifont

提问by Andre

I've searched loads already and couldn't find an answer.

我已经搜索了负载,但找不到答案。

I have a normal UILabel, defined this way:

我有一个普通的 UILabel,定义如下:

    UILabel *totalColors = [[[UILabel alloc] initWithFrame:CGRectMake(5, 7, 120, 69)] autorelease];
    totalColors.text = [NSString stringWithFormat:@"%d", total];
    totalColors.font = [UIFont fontWithName:@"Arial-BoldMT" size:60];
    totalColors.textColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1.0];
    totalColors.backgroundColor = [UIColor clearColor];
    [self addSubview:totalColors];

And I wanted the horizontal spacing between letters, to be tighter, whilst mantaining the font size.

我希望字母之间的水平间距更紧,同时保持字体大小。

Is there a way to do this? It should be a pretty basic thing to do.

有没有办法做到这一点?这应该是一件非常基本的事情。

Cheers guys, Andre

干杯伙计们,安德烈

UPDATE:

更新:

So I was forced to do it like this:

所以我被迫这样做:

- (void) drawRect:(CGRect)rect 
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSelectFont (context, "Arial-BoldMT", 60, kCGEncodingMacRoman);
    CGContextSetCharacterSpacing (context, -10);
    CGContextSetTextDrawingMode (context, kCGTextFill);

    CGContextSetRGBFillColor(context, 221/255.0, 221/255.0, 221/255.0, 221/255.0);
    CGAffineTransform xform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
    CGContextSetTextMatrix(context, xform);

    char* result = malloc(17);
    sprintf(result, "%d", totalNumber);

    CGContextShowTextAtPoint (context, 0, 54, result, strlen(result));
}

But I need to align this to the right. I could do that manually if I knew the width of the drawn text, but it's proving near impossible to find that.

但我需要把它向右对齐。如果我知道绘制文本的宽度,我可以手动执行此操作,但事实证明几乎不可能找到它。

I've read about ATSU, but I couldn't find any examples.

我读过有关 ATSU 的文章,但找不到任何示例。

This sucks :/

这很糟糕:/

采纳答案by Andre

I've come up with a solution for the letter spacing and the alignment to the right.

我想出了一个解决字母间距和向右对齐的解决方案。

Here it goes:

它是这样的:

    NSString *number = [NSString stringWithFormat:@"%d", total];

    int lastPos = 85;

    NSUInteger i;
    for (i = number.length; i > 0; i--)
    {
        NSRange range = {i-1,1};
        NSString *n = [number substringWithRange:range];

        UILabel *digit = [[[UILabel alloc] initWithFrame:CGRectMake(5, 10, 35, 50)] autorelease];
        digit.text = n;
        digit.font = [UIFont fontWithName:@"Arial-BoldMT" size:60];
        digit.textColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1.0];
        digit.backgroundColor = [UIColor clearColor];
        [self addSubview:digit];

        CGSize textSize = [[digit text] sizeWithFont:[digit font]];
        CGFloat textWidth = textSize.width;

        CGRect rect = digit.frame;
        rect.origin.x = lastPos - textWidth;
        digit.frame = rect;

        lastPos = rect.origin.x + 10;
    }

The letter spacing is the "10" on the last line. The alignment comes from the lastPos.

字母间距是最后一行的“10”。对齐来自 lastPos。

Hope this helps anyone out there.

希望这可以帮助那里的任何人。

回答by Krizai

From iOS 6 you can use NSAttributedString in UILabel.

从 iOS 6 开始,您可以在 UILabel 中使用 NSAttributedString。

In attributed string you can use attribute NSKernAttributeName to set letter spacing

在属性字符串中,您可以使用属性 NSKernAttributeName 来设置字母间距

NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString: @"Test test test test "];
[attrStr addAttribute:NSKernAttributeName value:@(4.0) range:NSMakeRange(0, attrStr.length)];

UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, 300, 300, 100)];
label.attributedText = attrStr;

回答by user363349

I've extended UILabel to change the character spacing. This should work out the box and pulls font, text, color etc from the UILabel itself (proper coding!).

我扩展了 UILabel 以更改字符间距。这应该算出框并从 UILabel 本身中提取字体、文本、颜色等(正确的编码!)。

You may notice I draw the text twice, first with clear color. This is to auto center the text in the label. Whilst this may be inefficient - isn't it nice to be auto centered?

您可能会注意到我绘制了两次文本,第一次使用清晰的颜色。这是为了使标签中的文本自动居中。虽然这可能效率低下 - 自动居中不是很好吗?

Enjoy!

享受!

@interface RALabel : UILabel {
}
@end  

@implementation RALabel 

- (void) drawRect:(CGRect)rect 
{

    // Drawing code

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSelectFont (context, [self.font.fontName cStringUsingEncoding:NSASCIIStringEncoding], self.font.pointSize, kCGEncodingMacRoman);
    CGContextSetCharacterSpacing(context, 1);
    CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
    CGAffineTransform myTextTransform = CGAffineTransformScale(CGAffineTransformIdentity, 1.f, -1.f );
    CGContextSetTextMatrix (context, myTextTransform);

    // draw 1 but invisbly to get the string length.
    CGPoint p =CGContextGetTextPosition(context);
    float centeredY = (self.font.pointSize + (self.frame.size.height- self.font.pointSize)/2)-2;
    CGContextShowTextAtPoint(context, 0, centeredY, [self.text cStringUsingEncoding:NSASCIIStringEncoding], [self.text length]);
    CGPoint v =CGContextGetTextPosition(context);

    // calculate width and draw second one.
    float width = v.x - p.x;
    float centeredX =(self.frame.size.width- width)/2;
    CGContextSetFillColorWithColor(context, [self.textColor CGColor]);
    CGContextShowTextAtPoint(context, centeredX, centeredY, [self.text cStringUsingEncoding:NSASCIIStringEncoding], [self.text length]);

}

回答by CodeOverRide

In Swift:

在斯威夫特:

let myTitle = "my title"
let titleLabel = UILabel()
let attributes: NSDictionary = [
    NSFontAttributeName:UIFont(name: "HelveticaNeue-Light", size: 20),
    NSForegroundColorAttributeName:UIColor.whiteColor(),
    NSKernAttributeName:CGFloat(2.0)
]
let attributedTitle = NSAttributedString(string: myTitle, attributes: attributes as? [String : AnyObject])

titleLabel.attributedText = attributedTitle
titleLabel.sizeToFit()

回答by Zack

Not in any publicly available version of iPhone OS. ;-) If you are a current iPhone Developer, you can get an idea of where iPhone OS is going by looking through the "What's New" notes for iPhone OS 3.2.

不在任何公开可用的 iPhone 操作系统版本中。;-) 如果您是当前的 iPhone 开发人员,您可以通过查看 iPhone OS 3.2 的“新增功能”说明来了解 iPhone OS 的发展方向。

Update:iOS v3.2, which added support for kerning, was still under NDA when I posted this. For an update-to-date answer, see How to set kerning in iPhone UILabel.

更新:iOS v3.2 增加了对字距调整的支持,当我发布这篇文章时,它仍处于保密协议之下。有关最新的答案,请参阅如何在 iPhone UILabel 中设置字距调整