iOS 计算图文富文本的宽高

计算高度

因为富文本中带有网络图片,所以要计算出图片宽度的富文本宽高
1、网上很多方法我看都计算不出来,我再 img 标签后面给网络图片添加个宽度,就可以了(可能是因为我们的富文本不规范吧,img标签都没有设置width)
2. 计算宽高时候发现,p标签会导致高度偏高,所以我给替换掉了(如有大佬知道原因,或者能给出其他方法,请留言@我)
3.


/// html字符串   文本域宽度  字体大小
public func getAttriSize(text: String, width: CGFloat, font: UIFont) -> CGSize {
    
    
    var html = "<head><style>img{max-width:\(width) !important;height:auto}</style></head>\(text)"
    html = html.replacingOccurrences(of: "<img", with: "<img width=\"\(width)\"")
    html = html.replacingOccurrences(of: "<p>", with: "")
    html = html.replacingOccurrences(of: "</p>", with: "")
    
    var htmlString: NSMutableAttributedString? = nil
    do {
    
    
        if let data = html.data(using: .utf8) {
    
    
            htmlString = try NSMutableAttributedString(data: data, options: [
            NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
            NSAttributedString.DocumentReadingOptionKey.characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue)
            ], documentAttributes: nil)
        }
    } catch {
    
    
    }
    // 设置富文本字的大小
    htmlString?.addAttributes([
    NSAttributedString.Key.font: font
    ], range: NSRange(location: 0, length: htmlString?.length ?? 0))

    // 设置行间距
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 6
    htmlString?.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: htmlString?.length ?? 0))
    
    let attri = htmlString ?? NSMutableAttributedString(string: html)
    let htmlSize = attri.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)),
                                      options: [.usesLineFragmentOrigin, .usesFontLeading],
                                      context: nil).size 
    return htmlSize
}

问题

1 计算耗时,慎用

少量加载可以无视,大量就要慎重了,(如有大佬有解决方法,请留言@我)

2 计算宽度精度问题

宽度精度会丢失一点点,如要使用,稍微添加0.5的宽度可无视

3 图片宽度问题

必须要img 标签中有 width 或者 height ,没办法计算图片的真实高度

猜你喜欢

转载自blog.csdn.net/u014651417/article/details/124764887