Try adding this extension to UIImage
:
extension UIImage {
func resizeToBoundingSquare(_ boundingSquareSideLength : CGFloat) -> UIImage {
let imgScale = self.size.width > self.size.height ? boundingSquareSideLength / self.size.width : boundingSquareSideLength / self.size.height
let newWidth = self.size.width * imgScale
let newHeight = self.size.height * imgScale
let newSize = CGSize(width: newWidth, height: newHeight)
UIGraphicsBeginImageContext(newSize)
self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return resizedImage!
}
}
Say you have a 1024x1024 icon that you wish to resize as 40x40. Just do this:
var myIcon = UIImage(named: image)
myIcon = myIcon.resizeToBoundingSquare(40)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…