TheFlow_ TheFlow_ - 1 year ago 146
Swift Question

NSAttributedString: Fit image to container

I have a NSAttributedString which is made from HTML and it displays some images. The problem is that the images are bigger than the container and I wonder how to fit them in it.

Thanks for your help

Answer Source

I finally found how to do that:

content.enumerateAttribute(NSAttachmentAttributeName, inRange: NSMakeRange(0, content.length), options: NSAttributedStringEnumerationOptions(0)) { (value, range, stop) -> Void in
    if let attachement = value as? NSTextAttachment {
        let image = attachement.imageForBounds(attachement.bounds, textContainer: NSTextContainer(), characterIndex: range.location)
        let screenSize: CGRect = UIScreen.mainScreen().bounds
        if image.size.width > screenSize.width-2 {
            let newImage = image.resizeImage(screenSize.width-2/image.size.width)
            let newAttribut = NSTextAttachment()
            newAttribut.image = newImage
            content.addAttribute(NSAttachmentAttributeName, value: newAttribut, range: range)

The function resizeImage() is defined like that:

extension UIImage {
    func resizeImage(scale: CGFloat) -> UIImage {
        let newSize = CGSizeMake(self.size.width*scale, self.size.height*scale)
        let rect = CGRectMake(0, 0, newSize.width, newSize.height)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        return newImage
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download