ios 当设置contentMode为UIViewContentModeScaleAspectFit时,如何设置UIImageView左对齐或右对齐?

gkn4icbw  于 2023-08-08  发布在  iOS
关注(0)|答案(3)|浏览(171)

我想在UIImageView中使用UIViewContentModeScaleAspectFit时控制图像对齐。


的数据
例如,我在一个视图中有两个UIImageView,如上所述。这两个UIImageView的contentMode是UIViewContentModeScaleAspectFit。现在我想将图像3设置为右对齐,将图像4设置为左对齐,以便这两个图像可以在一起。
我尝试将contentMode设置为UIViewContentModeScaleAspect|UIViewContentModeLeft,但它使情况变得更糟。
任何建议都很感激。

hts6caw3

hts6caw31#

最后,我找到了UIImageViewAligned项目,可以解决这个问题。
感谢@Marchy,还有swift版本UIImageViewAlignedSwift

请注意,某些约束需要编辑,否则图像可能不会显示。

例如,“lessThanOrEqual”约束应更改为“equal”。

n3ipq98p

n3ipq98p2#

与其在图像视图中左对齐图像,不如通过编程方式向图像视图中添加宽度约束,这样就不会有“多余的空间”。
假设您有一个带有“AspectFit”内容模式的UIImageView,并在界面构建器中添加了一个固定高度约束。然后,在相关的视图控制器中,检查图像的纵横比,并应用必要的宽度约束将图像视图捕捉到所包含的图像。例如:

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    // UIImage loaded from somewhere...
    imageView.image = uiImage

    // Check the UIImageView for existing height constraints
    let heightConstraints = imageView.constraints.filter{$0.firstAttribute == .height}
    if let imageViewHeight = heightConstraints.first?.constant {

        // Calculate the width which would make the image view fit
        // the image perfectly, and constrain the view to that width.
        let desiredImageViewWidth = (imageViewHeight / uiImage.size.height) * uiImage.size.width
        imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: desiredImageViewWidth))
    }
}

字符串
要将此应用于您的问题,您可以将两个UIImageView限制为彼此相邻,为两者设置固定的高度限制(具有相同的值),然后使用上述代码编程设置宽度。

ncecgwcz

ncecgwcz3#

对于一些人来说,另一种选择可能是调整UIImageView上的内容拥抱优先级。在Interface Builder中,向UIImageView添加一个优先级较低的约束。
x1c 0d1x的数据
这将满足约束,直到添加图像。然后将UIImageView的Content Hugging Priority设置为高宽度值(如果您是顶部/底部对齐,则为高度)。



然后只需将UIImageView的内容模式设置为您想要的。希望这对你有帮助!

相关问题