Swift 3/4缩放UIImage的方法

时间:2022-06-01 12:56:50

给UIImage添加extension(兼容Swift3 和Swift 4)

extension UIImage {

    func scaled(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()!
    }
}

scaled()接收指定的尺寸缩放UIImage。

如果要按纵横比缩放到给定尺寸,可以添加以下extension:

extension UIImage {

    func scaleToFitSize(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))
        }
    }

}

使用:

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