how to set the UIImageView align left or right when set the contentMode to UIViewContentModeScaleAspectFit?

限于喜欢 提交于 2019-12-05 09:53:56

问题


I want to control the image alignment when using the UIViewContentModeScaleAspectFit in UIImageView.

For example, I have two UIImageView in one view as above.these two UIImageView's contentMode is UIViewContentModeScaleAspectFit. Now I want to set image 3 to align right and image 4 to align left, so that these two images can be together.

I try to set the contentMode to UIViewContentModeScaleAspect|UIViewContentModeLeft, but it make things worse.

Any suggestions are appreciated.


回答1:


Finally, I find UIImageViewAligned project which can work it out.

Thanks to @Marchy, there is also swift version UIImageViewAlignedSwift




回答2:


Rather than trying to left align the image within the image view, you could programatically add a width constraint to the image view so that there is no "excess space".

Suppose you have a UIImageView with "Aspect Fit" content mode, and a fixed height constraint added in the interface builder. Then, in the relevant view controller, check the aspect ratio of the image and apply the necessary width constraint to snap the image view to the contained image. E.g.:

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

To apply this to your problem, you could constrain your two UIImageViews to be next to one another, set a fixed height constraint for both (of the same value), and then programatically set the width using the above code.




回答3:


Another option for some people might be to adjust the Content Hugging Priority on the UIImageView. In Interface Builder add a constraint to the UIImageView with a low priority.

This will satisfy the constraints until an image is added. Then set the UIImageView's Content Hugging Priority to a high value for width (or height if you are top/bottom aligning).

Then just set the UIImageView's Content Mode to what you want. Hope this helps!



来源:https://stackoverflow.com/questions/18626816/how-to-set-the-uiimageview-align-left-or-right-when-set-the-contentmode-to-uivie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!