我找到了几个示例来调整图像大小,使其宽高比保持给定CGRect
,或者仅像this post中的宽度一样。但这些示例始终会创建一个看起来像scaleAspectFit
内容模式的新图像。我想在scaleAspectFill
内容模式中获得一个,但我找不到任何示例。
答案 0 :(得分:3)
我已将其用于我的一个项目。
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!
}
}