boundingRectWithSize 的使用, 計算UILable高度, 包含Emoji及多屬性string.


iOS的文字高度計算一直是個問題, 蘋果也一直在改, 這幾天看了一下 boundingRectWithSize 方法.

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(6_0);

  

踩了幾個坑后, 總算找到比較好的使用方法.

 

參考: http://stackoverflow.com/questions/13621084/boundingrectwithsize-for-nsattributedstring-returning-wrong-size

使用時的注意事項:

1: NSAttributedString 的每個部分都要至少設置兩個屬性: 

NSFontAttributeName

NSForegroundColorAttributeName

 

2: NSStringDrawingOptions 的值, 在多行的情況下, 至少要有   

NSStringDrawingUsesLineFragmentOrigin

NSStringDrawingUsesFontLeading

 

3: 如果文字中可能會出現emoji表情的話, emoji的高度比文字要高一點點, 

我的方法是簡單的在高度基礎上加了兩個像素.  

(用CoreText可能會好一些, 但相對復雜.)

 

 

 

附代碼:

 

NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:fullDescAndTagStr];

NSRange allRange = [fullDescAndTagStr rangeOfString:fullDescAndTagStr];
[attrStr addAttribute:NSFontAttributeName
                value:[UIFont systemFontOfSize:13.0]
                range:allRange];
[attrStr addAttribute:NSForegroundColorAttributeName
                value:[UIColor blackColor]
                range:allRange];

NSRange destRange = [fullDescAndTagStr rangeOfString:tagStr];
[attrStr addAttribute:NSForegroundColorAttributeName
                value:HEXCOLOR(0x009cdd)
                range:destRange];





CGFloat titleHeight;

NSStringDrawingOptions options =  NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(labelWidth, CGFLOAT_MAX)
                                    options:options
                                    context:nil];
titleHeight = ceilf(rect.size.height);

return titleHeight+2;  // 加兩個像素,防止emoji被切掉.

  

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM