0

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 ?

Elstine P
  • 340
  • 4
  • 22
  • I think you for this you need to get the height of image "UIimage.size" then after according to the device.scale you can get the actual size of image which need to render on the screen. – Sumeet Mourya Jun 19 '18 at 11:35
  • any ideas on how do I do that ? – Elstine P Jun 19 '18 at 11:36
  • 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. – Sumeet Mourya Jun 19 '18 at 11:38
  • Possible duplicate of [How to know the image size after applying aspect fit for the image in an UIImageView](https://stackoverflow.com/questions/6278876/how-to-know-the-image-size-after-applying-aspect-fit-for-the-image-in-an-uiimage) – DonMag Jun 19 '18 at 13:06

2 Answers2

1

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

Anton Filimonov
  • 1,655
  • 15
  • 19
0

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.
Sumeet Mourya
  • 434
  • 1
  • 7
  • 23
  • Basically that's not true because UIImage object itself has scale property and in case of creating image with `init(named:)` you most likely get an image of scale which is equal to the screen scale (if such image exists in your bundle). So if what you need is image height scaled to current screen, then it is whether `image.size.height` if `image.scale == UIScreen.main.scale` or `image.size.height * image.scale / scaleFator` in common case – Anton Filimonov Jun 20 '18 at 06:30