2

I need to resize my UIImage according to the size of UIImageView. My image is too small, so i need to scale it up. I was not able to do it using:

self.firstImage.contentMode = UIViewContentModeScaleAspectFit;

Please help.

coder
  • 10,236
  • 17
  • 70
  • 124
Shradha
  • 951
  • 3
  • 12
  • 38

4 Answers4

4

You just need to set the frame of your UIImageView and set the contentMode to one of the resizing options.

Or you can use this utility method, if you actually need to resize an image:

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

Or look at these links :

http://nanostuffs.com/Blog/?p=586

http://www.abdus.me/ios-programming-tips/resize-image-in-ios/

Vineet Singh
  • 4,793
  • 1
  • 29
  • 39
  • I see this code posted everywhere and it's great, but I use the frame size of the uibutton into which the image is being set and the image gets sized squished if the sizes are different. For example, if the image size is 1200x1600 and the uibutton frame is 80x80, the image resizes narrower. Can anyone help with this? Thanks. – Rod Aug 01 '14 at 21:09
2

In Swift 3.0 , it will be

func imageWithImage(image:UIImage, scaledToSize newSize:CGSize ) -> UIImage {

    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
    image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.width))
    let newImage : UIImage  = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext();
    return newImage;

}
Ghulam Rasool
  • 3,787
  • 2
  • 24
  • 38
0

Please follow below link. Hope you will get solution.

How to use UIImageView Content Mode ?

Thanks.

Community
  • 1
  • 1
sagarcool89
  • 1,366
  • 8
  • 16
0

try with this:

self.imageView.contentMode   = UIViewContentModeScaleAspectFill;
self.imageView.clipsToBounds = YES;
Camo
  • 1,780
  • 14
  • 12