如果我试图找出字符串的宽度(以像素为单位)
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.
}
}
如果有人能提出解决方案,我将不胜感激。
最佳答案
经过一些测试后,看起来调用 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]];
当“Hello”返回 28 而“There”返回 32 时返回 59。
关于iphone - NSString sizeWithFont,问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11524492/