How to resize UIImageView based on UIImage's size/ratio in Swift 3?

前端 未结 8 1533
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 19:01

I have a UIImageView and the user is able to download UIImages in various formats. The issue is that I need the UIImageView to resize

8条回答
  •  [愿得一人]
    2020-11-28 19:20

    I spent many hours on this, and I finally got a solution that worked for me (Swift 3):

    • in IB, I set UIImageView's 'Content Mode' to 'Aspect Fit'
    • in IB, I set UIImageView's width constraint to be equal to whatever you want (in my case, the view's width)
    • in IB, I set UIImageView's height constraint to be equal to 0, and create a referencing outlet for it (say, constraintHeight)

    Then, when I need to display the image, I simply write the following (sampled from answers above):

    let ratio = image.size.width / image.size.height
    let newHeight = myImageView.frame.width / ratio
    constraintHeight.constant = newHeight
    view.layoutIfNeeded()
    

    Basically, this ensures that the image fills the UIImageView's width and forces the UIImageView's height to be equal to the image's height after it scaled

提交回复
热议问题