【问题标题】:how to set the UIImageView align left or right when set the contentMode to UIViewContentModeScaleAspectFit?将contentMode设置为UIViewContentModeScaleAspectFit时如何设置UIImageView左对齐或右对齐?
【发布时间】:2013-09-05 02:32:58
【问题描述】:

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

例如,我在上面的一个视图中有两个UIImageView。这两个UIImageView 的contentMode 是UIViewContentModeScaleAspectFit。现在我想将图像 3 设置为右对齐,图像 4 设置为左​​对齐,这样这两个图像就可以在一起了。

我尝试将 contentMode 设置为 UIViewContentModeScaleAspect|UIViewContentModeLeft,但这会让事情变得更糟。

欢迎提出任何建议。

【问题讨论】:

    标签: ios uiview uiimageview uiimage


    【解决方案1】:

    最后,我找到了UIImageViewAligned 可以解决的项目。

    感谢@Marchy,还有swift版UIImageViewAlignedSwift

    【讨论】:

    • 这是一个用 Swift 重写的版本:github.com/sochalewski/UIImageViewAlignedSwift
    • @Marchy 非常感谢您的快速版本。它帮助了我。我认为您应该将其作为单独的答案发布,因为有人可能无法通过评论。
    • 这个库的 Swift 实现 imageView.contentMode = .scaleAspectFit imageView.setValue("true", forKeyPath: "alignTop")
    【解决方案2】:

    您可以通过编程方式向图像视图添加宽度约束,而不是尝试在图像视图中左对齐图像,以免出现“多余空间”。

    假设您有一个具有“Aspect Fit”内容模式的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))
        }
    }
    

    要将此应用于您的问题,您可以将两个 UIImageViews 限制为彼此相邻,为两者设置一个固定的高度约束(具有相同的值),然后使用上述代码以编程方式设置宽度.

    【讨论】:

      【解决方案3】:

      对于某些人来说,另一个选择可能是调整UIImageView 上的Content Hugging Priority。在 Interface Builder 中,向 UIImageView 添加一个低优先级的约束。

      这将满足约束,直到添加图像。然后将 UIImageView 的 Content Hugging Priority 设置为较高的宽度值(或高度,如果您是顶部/底部对齐)。

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

      【讨论】:

      • 这实际上对我有用,只是稍作调整!
      猜你喜欢
      • 2011-11-25
      • 2015-10-07
      • 1970-01-01
      • 2021-02-21
      • 2012-03-10
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多