'Resize an image with drawInRect while maintaining the aspect ratio like Scale Aspect Fill?

I would like to resize an image with drawInRect method, but I would also like to maintain the right aspect ratio, while filling completely the given frame (as .ScaleAspectFill does for UIViewContentMode). Anyone has a ready answer for this?

Here is my code (pretty straightforward...):

func scaled100Image() -> UIImage {
    let newSize = CGSize(width: 100, height: 100)
    UIGraphicsBeginImageContext(newSize)
    self.pictures[0].drawInRect(CGRect(x: 0, y: 0, width: 100, height: 100))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}


Solution 1:[1]

The Objective-C version, if someone need it(Paste this code inside a UIIMage category):

- (void) drawInRectAspectFill:(CGRect) recto {

CGSize targetSize = recto.size;
if (targetSize.width <= CGSizeZero.width && targetSize.height <= CGSizeZero.height ) {
    return  [self drawInRect:recto];
}

float widthRatio = targetSize.width  / self.size.width;
float heightRatio   = targetSize.height / self.size.height;
float scalingFactor = fmax(widthRatio, heightRatio);
CGSize newSize = CGSizeMake(self.size.width  * scalingFactor, self.size.height * scalingFactor);

UIGraphicsBeginImageContext(targetSize);

CGPoint origin = CGPointMake((targetSize.width-newSize.width)/2,(targetSize.height - newSize.height) / 2);

[self drawInRect:CGRectMake(origin.x, origin.y, newSize.width, newSize.height)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

[scaledImage drawInRect:recto];

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Totka