如何以编程方式调整 UIImage 的大小,就像设置 scaleAspectFill 内容模式一样?
How to resize UIImage programmatically to be like setting scaleAspectFill content mode?
我找到了几个调整图像大小的例子,在给定特定 CGRect
的情况下保持其纵横比,或者例如仅像 this post 中的宽度。但是这些示例总是创建一个看起来像 scaleAspectFit
内容模式的新图像。我想在 scaleAspectFill
内容模式中得到一个,但我没有找到任何示例。
我已经将它用于我的一个项目。
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!
}
}
我找到了几个调整图像大小的例子,在给定特定 CGRect
的情况下保持其纵横比,或者例如仅像 this post 中的宽度。但是这些示例总是创建一个看起来像 scaleAspectFit
内容模式的新图像。我想在 scaleAspectFill
内容模式中得到一个,但我没有找到任何示例。
我已经将它用于我的一个项目。
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!
}
}