gpt4 book ai didi

swift - 如何根据图像调整 UIImaveView 的大小?

转载 作者:行者123 更新时间:2023-11-28 13:46:22 26 4
gpt4 key购买 nike

我想让 UIImageView 尽可能多地填充容器,但其中的图片应保持其纵横比,并且容器应适合其中图片的大小。

这是它现在不起作用时的样子的图片:

https://imgur.com/a/S9WSHmc

我已经解决了这个问题,但只是在第一次加载 View 时,当我更改 imageView 的图像时它变得越来越小。

我用这个扩展解决了它:

https://www.hackingwithswift.com/example-code/uikit/how-to-find-an-aspect-fit-images-size-inside-an-image-view

因此,当获得 UIImage 时,我调用布局方法来布局我的 UIView,然后在 UIImageView 中设置图像。接下来,在父级 UIView 的绘制方法中,我计算了 UIImageViewcontentClippingRect,然后将 UIImageView 的约束设置为 contentClippingRect 并再次布局。

当 imageView 中没有图像时,我的布局方法将 UIImageView 的约束重置为整个容器的约束。

但如前所述,当我更改图片时它不起作用,并且在更改图像时我遇到了约束问题。

这是我尝试过的:

var image: UIImage? {
didSet {
photoView.image = nil
layout()
photoView.image = image
}
}

override func draw(_ rect: CGRect) {
if photoView.image != nil {
setPictureFrame()
layout()
}
}

private func setPictureFrame() {
let photoRect = photoView.contentClippingRect
photoView.clearConstraints()

photoView.heightAnchor.constraint(equalToConstant: photoRect.height).isActive = true
photoView.widthAnchor.constraint(equalToConstant: photoRect.width).isActive = true
}

private func layout() {

var layoutConstraints: [NSLayoutConstraint] = []

if photoView.image == nil {
photoView.clearConstraints()
photoView.constraintsFillWhole(view: photoViewContainer)
}

layoutConstraints += [
photoView.centerXAnchor.constraint(equalTo: self.centerXAnchor),
photoView.centerYAnchor.constraint(equalTo: photoViewContainer.centerYAnchor),
]
NSLayoutConstraint.activate(layoutConstraints)
}

非常感谢您的帮助!

最佳答案

您也可以根据 Storyboard 制作纵横比。转到该 imageView 的属性检查器,您将从那里找到内容模式。这是一个例子 enter image description here

您也可以通过编程方式执行此操作。

快速

yourImageView.contentMode = .scaleAspectFill // or you can use .scaleToFill

对于 objective-c

yourimageView.contentMode = UIViewContentModeScaleAspectFit;

以下是您可以以编程方式使用的一些内容模式。

UIViewContentModeScaleToFill,
UIViewContentModeScaleAspectFit,
UIViewContentModeScaleAspectFill,
UIViewContentModeRedraw,
UIViewContentModeCenter,
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight,

关于swift - 如何根据图像调整 UIImaveView 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55355439/

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