How to resize an UIImage while maintaining its Aspect Ratio

Viewed 31193

I want to resize a UIImage with maintaining its Aspect Ratio. I have written the following code, but it is not working as expected.

Code

-(UIImage * ) scaleImage: (UIImage * ) image toSize: (CGSize) targetSize {

    CGFloat scaleFactor = 1.0;
    if (image.size.width > targetSize.width || image.size.height > targetSize.height)
        if (!((scaleFactor = (targetSize.width / image.size.width)) > (targetSize.height / image.size.height))) //scale to fit width, or
            scaleFactor = targetSize.height / image.size.height; // scale to fit heigth.
    UIGraphicsBeginImageContext(targetSize);
    CGRect rect = CGRectMake((targetSize.width - image.size.width * scaleFactor) / 2, (targetSize.height - image.size.height * scaleFactor) / 2,
        image.size.width * scaleFactor, image.size.height * scaleFactor);
    [image drawInRect: rect];
    UIImage * scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

What exactly is wrong here?

6 Answers

In Swift 5 you can use scaleAspectFit on the contentMode attribute.

let photo = UIImage(imageLiteralResourceName: "your_img_name")
let photoImageView = UIImageView(image: photo)     
        
photoImageView.contentMode = .scaleAspectFit
Related