2017-05-25 28 views
1

我發現了幾個例子來調整圖像的大小,使其縱橫比保持爲CGRect,或者只有像this post那樣的寬度。但是這些示例總是會創建一個類似於scaleAspectFit內容模式的新圖像。我想得到一個像scaleAspectFill內容模式,但我沒有找到任何示例。如何以編程方式調整UIImage的大小,就像設置scaleAspectFill內容模式一樣?

+0

我做了這件事,請檢查出來,希望它可以幫助你 https://stackoverflow.com/a/43891737/4918968 –

回答

2

我已經將這個用於我的一個項目。

extension UIImage 
{ 
    func imageWithSize(size:CGSize) -> UIImage 
    { 
     var scaledImageRect = CGRect.zero 

     let aspectWidth:CGFloat = size.width/self.size.width 
     let aspectHeight:CGFloat = size.height/self.size.height 

     //max - scaleAspectFill | min - scaleAspectFit 
     let aspectRatio:CGFloat = max(aspectWidth, aspectHeight) 

     scaledImageRect.size.width = self.size.width * aspectRatio 
     scaledImageRect.size.height = self.size.height * aspectRatio 
     scaledImageRect.origin.x = (size.width - scaledImageRect.size.width)/2.0 
     scaledImageRect.origin.y = (size.height - scaledImageRect.size.height)/2.0 

     UIGraphicsBeginImageContextWithOptions(size, false, 0) 

     self.draw(in: scaledImageRect) 

     let scaledImage = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 

     return scaledImage! 
    } 
} 
相關問題