如何在文本视图中调整比例UIImageView的大小,例如Scale Aspect Fit swift?

问题描述 投票:0回答:1

嘿,我创建了一个textview,我可以在此textview中添加图像。此图像的宽度等于textview的宽度。但是我想给这个ImageView一个最大的高度,我想像内容模式比例方面适合显示图像,但它显示了拉伸(压缩方面填充)如何解决这种情况?如下代码

  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
swift uiimageview uitextview aspect-ratio nstextattachment
1个回答
1
投票

这是计算aspectFit比率的新高度的方法:

    // 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
© www.soinside.com 2019 - 2024. All rights reserved.