Fitting a UIImage in UIImageView

11,125

Solution 1

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/

Solution 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;

}
Share:
11,125
Shradha
Author by

Shradha

Pretty new to iOS Development, but im luvin it..!!

Updated on June 04, 2022

Comments

  • Shradha
    Shradha almost 2 years

    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.

  • Rod
    Rod over 9 years
    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.
  • Camo
    Camo over 9 years
    clipsToBounds is a UIView property and UIImageView extends UIView.
  • BDR
    BDR over 9 years
    typo: should be clipsToBounds instead of clipToBounds