The simplest way to resize an UIImage?

前端 未结 30 2607
迷失自我
迷失自我 2020-11-21 22:38

In my iPhone app, I take a picture with the camera, then I want to resize it to 290*390 pixels. I was using this method to resize the image :

UIImage *newI         


        
30条回答
  •  孤街浪徒
    2020-11-21 22:57

    This is an UIImage extension compatible with Swift 3 and Swift 4 which scales image to given size with an aspect ratio

    extension UIImage {
    
        func scaledImage(withSize size: CGSize) -> UIImage {
            UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
            defer { UIGraphicsEndImageContext() }
            draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
            return UIGraphicsGetImageFromCurrentImageContext()!
        }
    
        func scaleImageToFitSize(size: CGSize) -> UIImage {
            let aspect = self.size.width / self.size.height
            if size.width / aspect <= size.height {
                return scaledImage(withSize: CGSize(width: size.width, height: size.width / aspect))
            } else {
                return scaledImage(withSize: CGSize(width: size.height * aspect, height: size.height))
            }
        }
    
    }
    

    Example usage

    let image = UIImage(named: "apple")
    let scaledImage = image.scaleImageToFitSize(size: CGSize(width: 45.0, height: 45.0))
    

提交回复
热议问题