【发布时间】:2012-07-18 00:20:23
【问题描述】:
如果我尝试找出字符串的像素宽度
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.
}
}
如果有人能提出解决方案,我将非常感激。
【问题讨论】:
-
我认为您在 for 循环中的短语末尾添加了一个额外的 @" "。这可能就是您获得更大宽度的原因。
-
感谢@frowing,但这不是问题。
-
space是一个棘手的事情,因为space的大小在单词之间是不一样的,它的当前大小取决于space前后的字母。 (尝试深入了解字体的几何形状以获取更多信息。)
标签: iphone objective-c ios ios5 ios4