如何在文本视图中调整缩放UIImageView的大小,如缩放Aspect Fit swift



嘿,我创建了一个文本视图,可以在这个文本视图中添加图像。此图像的宽度等于文本视图的宽度。但我想给这个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

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

最新更新