[英]Change size of UIImageView to fit different UIImages
So I have my UIImageView which is called imgView
. 所以我有我的UIImageView,它称为imgView
。 Basically the user can add his own images to this view and save it again to his own gallery. 基本上,用户可以将自己的图像添加到此视图,然后再次将其保存到自己的画廊。
Because I don't know beforehand what the sizes the images from the User are the imgView
should change it's size everytime to perfectly fit the image with aspectFit. 因为我事先不知道来自User的图像的大小是多少,因此imgView
应该每次更改其大小以使图像与AspectFit完全匹配。 If the image is small the imgView
shrinks so it doesn't take up much space etc. 如果图像较小,则imgView
缩小,因此不会占用太多空间等。
I have used this code in my viewDidLoad
to achieve it but it doesn't do anything: 我已经在viewDidLoad
使用以下代码来实现它,但是它什么也没做:
imgView.frame.size.width = imgView.image?.size.width
imgView.frame.size.height = imgView.image?.size.height
or 要么
imgView.bounds.size = imgView.image?.size
What should I do differently? 我应该怎么做?
Edit for alexburtnik's answer: 编辑alexburtnik的答案:
In the Simulator: 在模拟器中:
I changed the background in my Image View to green. 我将“图像视图”中的背景更改为绿色。 So right now it fills out the whole screen but it the view shouldn't be larger than the image itself. 因此,现在它会填满整个屏幕,但视图的宽度不应大于图像本身。
Update width & height constraints: 更新宽度和高度限制:
I assume you're using autolayout. 我认为您正在使用自动版式。 If so, you should change constraints' constant
values instead of setting frames manually. 如果是这样,您应该更改约束的constant
量值,而不是手动设置框架。 Here is an example: 这是一个例子:
class ImageViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
@IBOutlet weak var widthConstraint: NSLayoutConstraint!
func setImage(image: UIImage) {
imageView.image = image
let screenSize = UIScreen.main.bounds.size
let imageAspectRatio = image.size.width / image.size.height
let screenAspectRatio = screenSize.width / screenSize.height
if imageAspectRatio > screenAspectRatio {
widthConstraint.constant = min(image.size.width, screenSize.width)
heightConstraint.constant = widthConstraint.constant / imageAspectRatio
}
else {
heightConstraint.constant = min(image.size.height, screenSize.height)
widthConstraint.constant = heightConstraint.constant * imageAspectRatio
}
view.layoutIfNeeded()
}
}
Note, that you also have to drag outlets for width
and height
constraints from storyboard to your viewController
请注意,您还必须将情节viewController
width
和height
限制的出口从情节viewController
拖动到viewController
Another solution without resizing UIImageView: 无需调整UIImageView大小的另一种解决方案:
If other UI elements don't rely on UIImageView's frame and the only thing you care about is image appearance, you can just set content mode to Center
or Top
/ Bottom
/ Right
/ Left
etc: 如果其他UI元素不依赖UIImageView的框架,并且您只关心图像外观,则可以将内容模式设置为“ Center
或“ Top
/ Bottom
/ Right
/ Left
等:
Just set UIImageView's background to clear color 只需设置UIImageView的背景即可清除颜色
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.