如果我试图找出像素宽度为一个字符串的NSString sizeWithFont,问题
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循环中在短语的末尾增加了一个额外的@“”。这可能就是为什么你获得更大的宽度。 – 2012-07-17 14:26:31
谢谢@frowing,但这不是问题。 – samfisher 2012-07-17 16:31:28
“空间”是一件棘手的事情,因为这两个词之间的“空间”大小不一样,它的当前大小取决于“空间”前后的字母。 (尝试挖掘字体的几何形状以获取更多信息。) – holex 2012-07-17 16:36:13