2012-12-01 88 views
18

我想採用標準UILabel並增加字體大小以填充垂直空間。以靈感來自於接受的答案爲這個question,我定義上的UILabel子類此的drawRect實現:縮放字體大小以垂直放入UILabel

- (void)drawRect:(CGRect)rect 
{ 
    // Size required to render string 
    CGSize size = [self.text sizeWithFont:self.font]; 

    // For current font point size, calculate points per pixel 
    float pointsPerPixel = size.height/self.font.pointSize; 

    // Scale up point size for the height of the label 
    float desiredPointSize = rect.size.height * pointsPerPixel; 

    // Create and assign new UIFont with desired point Size 
    UIFont *newFont = [UIFont fontWithName:self.font.fontName size:desiredPointSize]; 
    self.font = newFont; 

    // Call super 
    [super drawRect:rect]; 
} 

但因爲它縮放字體超出標籤的底部,這是行不通的。如果你想複製這個,我開始使用標籤289x122(寬x高),Helvetica作爲字體,起始點大小爲60,可以很好地貼在標籤上。下面是使用字符串「{汞柱」從標準的UILabel和我的子類輸出例如:

uilabel

uilabel subclass

我已經看了字體伸伸和,試圖縮放考慮這些在不同的組合,但仍然沒有任何運氣。任何想法,這是不同的字體具有不同的下行和上行長度?

回答

12

您的pointsPerPixel計算是錯誤的方式時,它應該是...

float pointsPerPixel = self.font.pointSize/size.height; 

而且,也許這代碼應該是layoutSubviews作爲唯一的時間的字體應該改變的是幀大小時變化。

+1

好吧......這是一個令人尷尬的簡單錯誤。感謝您的發現。 – user524261

+0

我試着在'layoutSubviews'中實現它,但我不認爲它可以工作。我認爲原因是給UILabel子類分配一個新的字體會觸發另一個'layoutSubviews'的調用,這是有問題的。在我的實現中,我的一個應用程序隊列被鎖定。 – user444731

0

我不知道是否它的舍入錯誤逐漸上升到下一個更大的字體大小。你能稍微調整rec.size.height嗎?喜歡的東西:

float desiredPointSize = rect.size.height *.90 * pointsPerPixel; 

更新:你pointPerPixel計算是倒退。你實際上是通過字體點來分割像素,而不是像素點。交換這些,每次都有效。就爲了徹底性,這是我測試的樣本代碼:這縮放和適合標籤盒內每一個我測試了大小不等40pt到60pt字體

//text to render  
NSString *soString = [NSString stringWithFormat:@"{Hg"]; 
UIFont *soFont = [UIFont fontWithName:@"Helvetica" size:12]; 

//box to render in 
CGRect rect = soLabel.frame; 

//calculate number of pixels used vertically for a given point size. 
//We assume that pixel-to-point ratio remains constant. 
CGSize size = [soString sizeWithFont:soFont]; 
float pointsPerPixel; 
pointsPerPixel = soFont.pointSize/size.height; //this calc works 
//pointsPerPixel = size.height/soFont.pointSize; //this calc does not work 

//now calc which fontsize fits in the label 
float desiredPointSize = rect.size.height * pointsPerPixel; 
UIFont *newFont = [UIFont fontWithName:@"Helvetica" size:desiredPointSize]; 

//and update the display 
[soLabel setFont:newFont]; 
soLabel.text = soString; 

。當我反轉計算時,我看到相同的結果,字體對於框太高。

+0

由於我們使用float pointSize值,因此沒有對整數進行四捨五入。即使如此,fontSize也超出了整個pointSize。同意你可以縮小一個因子,但這比真實計算更具吸引力,因字體而異。 – user524261