0

如果我尝试找出字符串的像素宽度

CGSize sz = [@"Test text to hilight without new line for testing" sizeWithFont:CGTextLabel.font];

NSLog(NSStringFromCGSize(sz));

输出为:CoregraphicsDrawing[3306:f803] {339, 21}

如果我尝试用空格分隔字符串@“”并循环它以添加每个单词的宽度+每个单词后的空格宽度,总宽度是不同的
CoregraphicsDrawing[3306:f803] 351.000000

请检查我正在逐字计算宽度的代码:

str = @"Test text to hilight without new line for testing";


    self.words = [NSMutableArray arrayWithArray:[str componentsSeparatedByString:@" "]];

    CGFloat pos = 0;
    [self.rects addObject:[NSValue valueWithCGPoint:CGPointMake(0, 0)]];
    for(int i = 0; i < [self.words count]; i++)
    {
        NSString *w = [self.words objectAtIndex:i];
        NSLog(w);
        CGSize sz = [w sizeWithFont:CGTextLabel.font];
        pos += sz.width;
        pos += [@" " sizeWithFont:CGTextLabel.font].width;

        if(i != [self.words count]-1)
        {

            [self.rects addObject:[NSValue valueWithCGPoint:CGPointMake(pos, 0)]];
        }
        else {
            NSLog(@"%f",pos); //here actual calculated width is printed. 
        }

    }

如果有人可以提出解决方案,我将非常感激。

4

1 回答 1

3

在做了一些测试之后,它看起来像sizeWithFont:只用一个空格调用,增加了额外的空间,并且没有将它视为字符之间的空格。这就是我尝试使用systemFont.

因此,每次使用[@" " sizeWithFont:CGTextLabel.font].width;时,您都不会获得字符之间空格的大小,但很可能还会在结尾处获得一些额外的位。我注意到这一点使用以下内容:

CGSize size1 = [@"Hello There" sizeWithFont:[UIFont systemFontOfSize:12]];
CGSize size2 = [@" " sizeWithFont:[UIFont systemFontOfSize:12]];
CGSize size3 = [@"Hello" sizeWithFont:[UIFont systemFontOfSize:12]];
CGSize size4 = [@"There" sizeWithFont:[UIFont systemFontOfSize:12]];

CGSize size5 = [@"Hello There Hello There" sizeWithFont:[UIFont systemFontOfSize:12]];

NSLog(NSStringFromCGSize(size1));
NSLog(NSStringFromCGSize(size2));
NSLog(NSStringFromCGSize(size3));
NSLog(NSStringFromCGSize(size4));
NSLog(NSStringFromCGSize(size5));

我从控制台返回了这个:

2012-07-17 10:57:40.513 TesterProject[62378:f803] {63, 15}
2012-07-17 10:57:40.514 TesterProject[62378:f803] {4, 15}
2012-07-17 10:57:40.514 TesterProject[62378:f803] {28, 15}
2012-07-17 10:57:40.514 TesterProject[62378:f803] {32, 15}
2012-07-17 10:57:40.514 TesterProject[62378:f803] {128, 15}

因此,仅空间就返回了 4 个“像素”的宽度。“Hello”返回 28,“There”返回 32。所以你会认为它是 64,但我得到了 63。所以空间占用 3 而不是 4。同样,当我执行“Hello There Hello There”时" 你会认为我会得到 63*2 + 4 的空间 = 130。相反,我得到了 63*2 + 2。所以在这种情况下,大部分时间空间实际上只占用 2-3 个“像素”,但如果我sizeWithFont:只要求@" "我得到 4。

字体并不总是为每个空间创建完全相同数量的间隙,这可能就是您遇到问题的原因。通过我的测试,我得到了将 2、3 甚至 4 个“像素”添加到不同单词组合的空间。我认为只有当你有整个短语时才应该使用这个调用,尝试将它们加在一起太难了。是否有另一种方法来创建您正在寻找的功能?

编辑:我还发现,仅将两个词放在一起会给您带来与单独使用它们不同的结果:

CGSize size = [@"HelloThere" sizeWithFont:[UIFont systemFontOfSize:12]];

返回 59,而“Hello”返回 28,“There”返回 32。

于 2012-07-17T16:20:23.247 回答