UIImage调整大小扩展

时间:2017-01-14 23:51:23

标签: swift swift-extensions

我做了一个扩展,让我调整UIImage的大小,但我想知道我是否正确调用它。扩展名在它自己的文件中,如下所示:

extension UIImage {
    func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
        let size = image.size

        let widthRatio  = targetSize.width  / image.size.width
        let heightRatio = targetSize.height / image.size.height

        // Figure out what our orientation is, and use that to form the rectangle
        var newSize: CGSize
        if(widthRatio > heightRatio) {
            newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
        } else {
            newSize = CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
        }

        // This is the rect that we've calculated out and this is what is actually used below
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

        // Actually do the resizing to the rect using the ImageContext stuff
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        image.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }
}

然后我这样称呼它:

img.resizeImage(image: img, targetSize: CGSize(width: 200.0, height: 200.0))

其中img是UIImage。 但是,对我来说,我在UIImage上调用一个函数,但也将它作为一个参数传递给我似乎很奇怪。这是正确的方法吗?还是有更简洁的方法?

1 个答案:

答案 0 :(得分:3)

您正在失去使用扩展程序的便利性。点击这里: https://www.hackingwithswift.com/read/24/2/creating-a-swift-extension

主要思想是你需要删除第一个参数并在函数代码中使用self