• iOS 计算字符串显示宽高度


    ObjC(Category of NSString):

    - (CGSize)getSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size{
        CGSize resultSize = CGSizeZero;
        if (self.length <= 0) {
            return resultSize;
        }
        NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
        style.lineBreakMode = NSLineBreakByWordWrapping;
        resultSize = [self boundingRectWithSize:CGSizeMake(floor(size.width), floor(size.height))//用相对小的 width 去计算 height / 小 heigth 算 width
                                        options:(NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin)
                                     attributes:@{NSFontAttributeName: font,
                                                  NSParagraphStyleAttributeName: style}
                                        context:nil].size;
        resultSize = CGSizeMake(floor(resultSize.width + 1), floor(resultSize.height + 1));//上面用的小 width(height) 来计算了,这里要 +1
        return resultSize;
    }

    Swift(Extension of NSString):

        func getSizeWithFont(_ font:UIFont,constrainedToSize size:CGSize) -> CGSize{
            
            if self.length == 0 { return CGSize.zero }
            
            let style = NSMutableParagraphStyle.init()
            style.lineBreakMode = .byWordWrapping
            
            let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
            let attributes = [NSFontAttributeName:font,NSParagraphStyleAttributeName:style]
            let bound = CGSize.init( floor(size.width), height: floor(size.height))
            
            let rect = self.boundingRect(with: bound, options: options, attributes: attributes, context: nil)
            let _size = CGSize.init( floor(rect.width + 1), height: floor(rect.height + 1))
            
            return _size
        }
    

      

  • 相关阅读:
    汽车行业如何利用大数据
    汽车行业如何利用大数据
    Linux下Gcc 的编译过程
    第一个GraphX程序
    VC++ 模拟&quot;CLICK事件&quot;关闭指定窗体
    基于Canvas的Char.js库使用
    VELT-0.1.6开发:载入根文件系统
    HDU 5411 CRB and puzzle (Dp + 矩阵高速幂)
    JavaScript图片裁剪
    C++ string中的几个小陷阱,你掉进过吗?
  • 原文地址:https://www.cnblogs.com/ficow/p/6418890.html
Copyright © 2020-2023  润新知