How to set image at the top avoiding space in UIimageView

I have a UIImageView with Aspect Fit content mode sized 220x155. I dynamically insert different images in different resolutions, but more and more the size of UIImageView. Because the content mode is set to Aspect Fit, the image is scaled relative to the ratio to fit the UIImageView.

My problem is that if, for example, the image inside the UIImageView is scaled to 220x100, I would like the UIImageView to be reduced from a height of 155 to 100 to avoid spaces between my elements.

How can i do this?

+4
source share
3 answers

I wrote this method to get the image viewing frame after loading the image. So, the requirements for me were the same as in your case:

1) view the image with content mode with matching support 2) get the exact frame of the image (this way you can move the image position)

Hope this helps:

- (CGRect) getFrameOfImage:(AsyncImageView *) imgView { if(!imgView.loaded) return CGRectZero; CGSize imgSize = imgView.image.size; CGSize frameSize = imgView.frame.size; CGRect resultFrame; if(imgSize.width < frameSize.width && imgSize.height < frameSize.height) { resultFrame.size = imgSize; } else { float widthRatio = imgSize.width / frameSize.width; float heightRatio = imgSize.height / frameSize.height; float maxRatio = MAX (widthRatio , heightRatio); NSLog(@"widthRatio = %.2f , heightRatio = %.2f , maxRatio = %.2f" , widthRatio , heightRatio , maxRatio); resultFrame.size = CGSizeMake(imgSize.width / maxRatio, imgSize.height / maxRatio); } resultFrame.origin = CGPointMake(imgView.center.x - resultFrame.size.width/2 , imgView.center.y - resultFrame.size.height/2); return resultFrame; } 

I use AsyncImageView here, but it will work just as well with UIImageView . It is important to remember that you need to call this method AFTER the image is loaded.

Hooray!

+2
source

It is very simple, you just need to get the actual image size, which can be done with

 UIImage *image = [UIImage imageName:@""]; 

you just need to set the frame For example: -

 imageView.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height); 

Hope this helps you.

+1
source

Once the image image is set to a new image (and thus scaled), you can get the height of the image inside the image (imageview.image.size.height) and set the height (frame) of the image accordingly.

0
source

Source: https://habr.com/ru/post/1437610/


All Articles