2017-04-12 54 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