Resize UIImage and change the size of UIImageView

I have this UIImageView 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 UIImageView 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 UIImageView 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 UIImageView.image, but of the wholeUIImageView, thus making its size totally adjustable to its content. Any help would be much appreciated, thanks!

iphone ios objective-c cocoa-touch uiimageview
share|improve this question
asked Feb 1 at 15:17
check ma answer.. –  Rajneesh071 Feb 2 at 9:15

add comment

5 Answers

up vote4down voteaccepted

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

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

I don’t check how it work, but guess all should be OK

share|improve this answer
edited Sep 14 at 9:07
answered Feb 1 at 15:48
  add comment
up vote4down vote
- (UIImage *)image:(UIImage*)originalImage scaledToSize:(CGSize)size
    //avoid redundant drawing
    if (CGSizeEqualToSize(originalImage.size, size))
        return originalImage;

    //create drawing context
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);

    [originalImage drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];

    //capture resultant image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    //return image
    return image;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s