簡體   English   中英

NSString sizeWithFont,問題

[英]NSString sizeWithFont, issue

如果我嘗試找出字符串的寬度(以像素為單位)

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]];

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM