gpt4 book ai didi

ios - AutoLayout:UIImageView 和 Aspect Fit 内容模式

转载 作者:行者123 更新时间:2023-12-02 06:19:12 27 4
gpt4 key购买 nike

我正在尝试将 UIImageView 放置在父 View 的中心。图像必须保持其原始宽高比,并且不应超出父级的边界。因此,横向图像应受到父级宽度的限制,纵向图像应根据需要占据尽可能多的垂直空间,并保持原始比例。

听起来对于 AutoLayout 来说是一个相当简单的任务,对吧?这是我的 UIImageView 设置:

  • 在父级中垂直居中
  • 在父级中水平居中
  • imageView.width <= superview.width
  • imageView.height <= superview.height

我还将 contentMode 设置为 Aspect Fit。对于小于设备屏幕的小图像,一切都非常有效,但由于某种原因,我的 UIImageView 比其底层 UIImage 对于大图像占用更多空间(注意绿色背景 - imageView.backgroundColor = [UIColor greenColor])。

enter image description here

为什么会发生这种情况?我不是自动布局专家,因为我的限制对我来说看起来很合理。如果我使用较小的图像(例如 200x400),则 UIImageView 在屏幕上恰好占据 200x400 点,没有额外的绿色区域。

我想添加边框和圆角,但在这种情况下显然无法正常工作。

最佳答案

发生这种情况是因为您将宽度和高度约束设置为<=。对于小图像,imageView 的框架计算没有任何问题,并且满足所有约束。但是当设置大图像时,imageView的大小将被设置为适合图像,但同时它受到 super View 的大小(屏幕大小)的限制。

  • 如果您确实知道宽高比,则可以将其设置为约束并你不会看到任何绿色背景。
  • 否则就留下你的约束不变并将背景颜色设置为清晰颜色。这任何未占用的区域都将是透明的,并且您设置的任何图像至少在一个维度上占据最大空间。

编辑:

可能不是最好的解决方案,有点老派。您可以添加严格的宽度和高度约束并使用图像的纵横比手动计算它们:

@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()
}

关于ios - AutoLayout:UIImageView 和 Aspect Fit 内容模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40142558/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com