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.
            Asked
            
        
        
            Active
            
        
            Viewed 899 times
        
    2
            
            
         
    
    
        AppsDev
        
- 12,319
- 23
- 93
- 186
- 
                    i had done this thing please check it out, hope it helps you https://stackoverflow.com/a/43891737/4918968 – Patel Jigar May 25 '17 at 12:30
1 Answers
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