How to get actual height of the image occupied in imageview for aspect fit

时间:2018-06-19 11:09:39

标签: ios uiimageview ios-autolayout aspect-fit

I would like to change the height of imageview based on how much height the image occupies in imageview.

I am using content mode Aspect Fit

Any ideas on how to do that ?

2 个答案:

答案 0 :(得分:1)

如果您希望图像填充整个图像视图,并且仅对该图像视图的宽度进行限制,那么以下代码应该会有所帮助:

let imageView: UIImageView = ...
let image: UIImage = ...
let imageSize = image.size
let scaleFactor = imageSize.height / imageSize.width
let imageViewHeight = imageView.bounds.width * scaleFactor

如果使用基于约束的布局,则甚至不需要imageViewHeight-您可以使用计算出的scaleFactor为imageView的高度设置相应的约束

答案 1 :(得分:0)

对我来说:

let image: UIImage = UIImage(named: "") 
print(image.size) // 400x400 
let scaleFator = UIScreen.main.scale //3 
let height = image.size.height / scaleFator ///here the actual height of image.