Search code examples
iosuiimageviewuiimageresizescale

How to resize UIImage programmatically to be like setting scaleAspectFill content mode?


I've found several examples to resize an image keeping its aspect ratio given a certain CGRect, or for example only the width like in this post. But those examples always create a new image that looks like in scaleAspectFit content mode. I would like to get one like in scaleAspectFill content mode but I don't find any example.


Solution

  • I have used this for one of my projects.

    extension UIImage
    {
        func imageWithSize(size:CGSize) -> UIImage
        {
            var scaledImageRect = CGRect.zero
    
            let aspectWidth:CGFloat = size.width / self.size.width
            let aspectHeight:CGFloat = size.height / self.size.height
    
            //max - scaleAspectFill | min - scaleAspectFit
            let aspectRatio:CGFloat = max(aspectWidth, aspectHeight)
    
            scaledImageRect.size.width = self.size.width * aspectRatio
            scaledImageRect.size.height = self.size.height * aspectRatio
            scaledImageRect.origin.x = (size.width - scaledImageRect.size.width) / 2.0
            scaledImageRect.origin.y = (size.height - scaledImageRect.size.height) / 2.0
    
            UIGraphicsBeginImageContextWithOptions(size, false, 0)
    
            self.draw(in: scaledImageRect)
    
            let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return scaledImage!
        }
    }