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

252 Views Asked by At

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

There are 2 best solutions below

1
On BEST ANSWER

for me :

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.
0
On

If you want your image to fill your whole image view and have limit only for width of that image view, then the following code should help:

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

If you use constraint based layout you don't even need the imageViewHeight - you can use calculated scaleFactor to set corresponding constraint for height of the imageView