how to resize an image or done as a NSAttributedString NSTextAttachment (or set its initital size)

前端 未结 5 1882
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 08:24

I have a NSAttributedString to which I am adding a NSTextAttachment. The image is 50w by 50h but I\'d like it to scale down to reflect the line height of the attributed stri

5条回答
  •  时光说笑
    2020-11-30 09:13

    If you need to resize a bunch of NSTextAttachment images while keeping their aspect ratio i've written a handy extension: http://hack.swic.name/convenient-nstextattachment-image-resizing

    extension NSTextAttachment {
        func setImageHeight(height: CGFloat) {
            guard let image = image else { return }
            let ratio = image.size.width / image.size.height
    
            bounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: ratio * height, height: height)
        }
    }
    

    Example usage:

    let textAttachment = NSTextAttachment()
    textAttachment.image = UIImage(named: "Image")
    textAttachment.setImageHeight(16) // Whatever you need to match your font
    
    let imageString = NSAttributedString(attachment: textAttachment)
    yourAttributedString.appendAttributedString(imageString)
    

提交回复
热议问题