Search code examples
swiftuiimageviewuitextviewaspect-rationstextattachment

How to resized scale UIImageView in textview like Scale Aspect Fit swift?


Hey I create a textview and I can add images in this textview.This image's width equal to textview's width. But I want to give a maximum height for this ImageView and I want to show the image like content mode scale aspect fit but it shows stretched(compressed aspect fill) how can I solve this situation ? Code like below

  let image = UIImageView()
  image.contentMode = .scaleAspectFit
  let imageAttachment = NSTextAttachment()
  let newImageWidth = self.textView.bounds.width
  let newImageHeight = 200
  imageAttachment.bounds = CGRect(x: 0, y: 0, width: Int(newImageWidth), height: newImageHeight)
  imageAttachment.image = image.image

Solution

  • This is how you would calculate the new height for an aspectFit ratio:

        // don't use "image" ... that's confusing
        let imageView = UIImageView()
    
        // assuming you set the image here
        imageView.image = UIImage(named: "myImage")
    
        guard let imgSize = imageView.image?.size else {
            // this will happen if you haven't set the image of the imageView
            fatalError("Could not get size of image!")
        }
    
        let imageAttachment = NSTextAttachment()
        let newWidth = self.textView.bounds.width
    
        // get the scale of the difference in width
        let scale = newWidth / imgSize.width
    
        // multiply image height by scale to get aspectFit height
        let newHeight = imgSize.height * scale
    
        imageAttachment.bounds = CGRect(x: 0, y: 0, width: newWidth, height: newHeight)
        imageAttachment.image = imageView.image