2017-04-12 37 views
-1

我有这样的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) 
    } 
+0

http://stackoverflow.com/questions/31314412/how-to- resize-image-in-swift –

回答

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 
}() 
+0

在函数中你可以用自己的图像引用图像 – muescha

+1

好点,我会编辑我的答案以反映这一点。谢谢@muescha –

+0

谢谢你的答案,但我仍然无法得到它的工作。我宣布它是你说的,但我不能让它在logoView中工作。我也从UIImageView重新定义了logoView到UIImage,但它不会让我添加UIImage作为子视图。我如何在UIImageView中调用它,或者如何实现它? – Ola