We’re are downloading images from the Internet and assigning them to an UIImageView object with aspectFit as it’s contentMode, something like [myImageView setImageWithURL:aURL].
However, aspect fit will resize the image and center it within the boundaries of the view. In other words when the image’s width is more than it’s height, then, there will be an space in between the bottom border of the UIImageView and the image itself.
Now, I want to include a label below the image without any type of space in between. How can this be achieved? I mean, we could resize the image beforehand and set the ImageView frame afterwards, but, since the image’s source is a URL this would required downloading the image first (A bunch of code that is already implemented by UIImageView categories).
Is there a way to tell UIImageView to “wrap” itself around the resizedImage, or is there a way to achieve this effect through constraints?
Thanks
As Cbiggin said you can use AutoLayout for that, but here is another way to achieve that
show loading and run this code in an async thread :
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
after image data has downloaded, use this code for getting the image’s width and height
UIImage *image = [UIImage imageWithData:imageData];
NSLog(@'image height: %f',image.size.height);
NSLog(@'image width: %f',image.size.width);
and you can calculate the height of your UIImageView, for example, if the width of your UIImageView is 320 and your image size is 1024×768 your UIImageView height will be 240
float imageViewHeight = imageView.frame.size.width/image.size.width * image.size.height
you can use imageViewHeight
Constraints should handle this. Make sure that your UIImageView only has constraints on the left & right sides (and also top I guess) and no constraints on the height. For your UILabel, it should have a constraint from its top to the bottom of the UIImageView (and whatever horizontal constraints you want on it).