【问题标题】:How to resized scale UIImageView in textview like Scale Aspect Fit swift?如何在文本视图中调整 UIImageView 的大小,如 Scale Aspect Fit swift?
【发布时间】:2020-06-17 11:17:02
【问题描述】:

嘿,我创建了一个 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】:

    这是计算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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2014-10-22
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多