UIImage通过扩展程序调整大小

时间:2017-04-12 00:21:56

标签: ios swift uiimage

我有这个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!
    }
}

我尝试通过调用下面的扩展程序来调整图像大小

 let logoView: UIImageView = {
    let LV = UIImageView()
    let thumbnail = resizeImage(image: "DN", CGSize.init(width:70, height:70))
    LV.image = thumbnail
    LV.contentMode = .scaleAspectFill
    LV.layer.masksToBounds = true
    return LV
}()

然而,Xcode不允许我调用调整大小功能扩展。如何正确调整图像大小?

   func setupViews() {


    addSubview(logoView)
  }

1 个答案:

答案 0 :(得分:2)

扩展中的函数不是独立函数,而是与它们扩展的东西相关联。在您的情况下,您正在向UIImage添加一个函数,但您将其称为独立函数。

要修复,你的功能应该是这样的:

extension UIImage {

    func resizeImage(targetSize: CGSize) -> UIImage {
        // the image is now “self” and not “image” as you original wrote
        ...
    }
}

你会称之为:

let logoView: UIImageView = {
    let LV = UIImageView()
    let image = UIImage(named: "DN")
    if let image = image {
        let thumbnail = image.resizeImage(CGSize.init(width:70, height:70))
        LV.image = thumbnail
        LV.contentMode = .scaleAspectFill
        LV.layer.masksToBounds = true
    }
    return LV
}()