我试图在父视图的中心放置一个< code>UIImageView。图像必须保持其原始的长宽比,也不应该超过父母的界限。因此,横向图像应该受到父图像宽度的限制,纵向图像应该在保持原始比例的情况下占据尽可能多的垂直空间。
对于AutoLayout来说,听起来似乎是一个非常简单的任务,对吗?以下是我对< code>UIImageView的设置:
我还将< code>contentMode设置为< code>Aspect Fit。对于比设备屏幕小的小图像,一切都很好,但由于某种原因,我的< code>UIImageView比它的底层< code>UIImage占用了更多的空间用于大图像(注意绿色背景-< code > imageview . background color =[ui color green color])。
为什么会这样?我不是自动布局专家,我的约束在我看来是合理的。如果我使用200x400这样的较小图像,那么< code>UIImageView在屏幕上正好占据200x400个点,没有多余的绿色区域。
我想添加边框和圆角,这显然不会在这种情况下正常工作。
这是因为您将宽度和高度限制设置为
编辑:
可能不是最好的解决方案,有点像老派。您可以添加严格的宽度和高度约束,并使用图像的方面手动计算它们Ratio:
@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()
}
尝试在Interface Builder Clip to Bound Image View中检查ImageView的“Clip to Bound”
你必须有一个明确的高度和宽度,而不是“