Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

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

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

I have a normal UILabel, defined this way:

    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.

This sucks :/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From iOS 6 you can use NSAttributedString in UILabel.

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

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...