zoukankan      html  css  js  c++  java
  • 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被切掉.
    

      

     

     

     

     

  • 相关阅读:
    html5 表單元素
    html5 表單輸入類型
    html5 服務器發送事件
    html5 web workers
    html5應用緩存
    html5 sessionStorage VS loaclStorage
    html5地理定位
    html5 画布和SVG的差别
    html5 SVG
    SQL-22 统计各个部门对应员工涨幅的次数总和,给出部门编码dept_no、部门名称dept_name以及次数sum
  • 原文地址:https://www.cnblogs.com/willbin/p/3955786.html
Copyright © 2011-2022 走看看