从 Swift 4.2 开始,
使用它,您将获得正确纵横比的非模糊调整大小的图像 -
class func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / 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)
//resizing the rect using the ImageContext
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
根据开发人员文档,以下方法使用指定的选项创建基于位图的图形上下文 -
func UIGraphicsBeginImageContextWithOptions(_ size: CGSize, _ opaque: Bool, _ scale: CGFloat)
参数-
size:新位图上下文的大小(以磅为单位)。这表示 UIGraphicsGetImageFromCurrentImageContext() 函数返回的图像大小。
opaque:一个布尔标志,指示位图是否不透明。
scale:应用于位图的比例因子。如果您指定值 0.0,则比例因子设置为设备主屏幕的比例因子。
参考- https://developer.apple.com/documentation/uikit/1623912-uigraphicsbeginimagecontextwitho