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

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


You should set bounds form attachment to resize image like this:

attachment.bounds = CGRectMake(0, 0, yourImgWidth, yourImgHeight)


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 fontlet imageString = NSAttributedString(attachment: textAttachment)yourAttributedString.appendAttributedString(imageString)


Look at subclassing NSTextAttachment and implementing the NSTextAttachmentContainer methods to return different sizes based on the text container supplied. By default, NSTextAttachment just returns the size of the image it is provided with.


matomo