如何像 Scale Aspect Fit swift 那样在 textview 中调整缩放 UIImageView 的大小?
How to resized scale UIImageView in textview like Scale Aspect Fit swift?
嘿,我创建了一个文本视图,我可以在此 textview.This 中添加图像,图像的宽度等于文本视图的宽度。但是我想给这个 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
嘿,我创建了一个文本视图,我可以在此 textview.This 中添加图像,图像的宽度等于文本视图的宽度。但是我想给这个 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