如果我試圖找出像素寬度爲一個字符串的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