gpt4 book ai didi

ios - 更改 UIImageView 的大小以适应不同的 UIImages

转载 作者:行者123 更新时间:2023-11-28 09:26:08 27 4
gpt4 key购买 nike

所以我有了名为 imgView 的 UIImageView。基本上,用户可以将自己的图像添加到此 View 并将其再次保存到自己的图库中。

因为我事先不知道来自用户的图像的尺寸是多少,imgView 应该每次都改变它的尺寸以完美地适应 aspectFit 的图像。如果图像很小,imgView 会缩小,因此不会占用太多空间等。

我在我的 viewDidLoad 中使用了这段代码来实现它,但它没有做任何事情:

imgView.frame.size.width = imgView.image?.size.width
imgView.frame.size.height = imgView.image?.size.height

imgView.bounds.size = imgView.image?.size

我应该怎么做?

编辑 alexburtnik 的回答:

现在这是我的代码:

在模拟器中:

enter image description here

我将 ImageView 中的背景更改为绿色。所以现在它填满了整个屏幕,但 View 不应大于图像本身。

最佳答案

更新宽度和高度限制:

我假设您正在使用自动版式。如果是这样,您应该更改约束的 constant 值,而不是手动设置框架。这是一个例子:

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

请注意,您还必须将 widthheight 约束的 socket 从 Storyboard拖到您的 viewController

另一种不调整 UIImageView 大小的解决方案:

如果其他 UI 元素不依赖 UIImageView 的框架,而你唯一关心的是图像外观,你可以将内容模式设置为 CenterTop/底部/右侧/左侧等:

enter image description here

只需将 UIImageView 的背景设置为清除颜色即可

关于ios - 更改 UIImageView 的大小以适应不同的 UIImages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40321463/

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