2

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.

AppsDev
  • 12,319
  • 23
  • 93
  • 186

1 Answers1

3

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!
    }
}
Sanket_B
  • 735
  • 9
  • 26