SergiusGee SergiusGee - 5 months ago 31
iOS Question

Resize UIImage and change the size of UIImageView

I have this

and I have the values of its max height and max width. What I want to achieve is that I want to take the image (with any aspect ratio and any resolution) and I want it to fit in the borders, so the picture does not exceed them, but it can shrink them as it wants. (marked red in the picture):

enter image description here

Right now the image fits the necessary size properly, but I have 2 worries:
1. The
is not equal the size of the resized image, thus leaving red background (and I don't want that)
2. If the image is smaller that the height of my
it is not resized to be smaller, it stays the same height.

Here's my code and I know its wrong:

UIImage *actualImage = [attachmentsArray lastObject];
UIImageView *attachmentImageNew = [[UIImageView alloc] initWithFrame:CGRectMake(5.5, 6.5, 245, 134)];
attachmentImageNew.image = actualImage;
attachmentImageNew.backgroundColor = [UIColor redColor];
attachmentImageNew.contentMode = UIViewContentModeScaleAspectFit;

So how do I dynamically change the size not only of the
, but of the whole
, thus making its size totally adjustable to its content. Any help would be much appreciated, thanks!


When you get the width and height of a resized image Get width of a resized image after UIViewContentModeScaleAspectFit, you can resize your imageView:

imageView.frame = CGRectMake(0, 0, resizedWidth, resizedHeight); =;

I haven't checked if it works, but I think all should be OK