Swift:
需求:图片等比例缩放,截取上部,不失真
代码如下:
extension UIImage {
//将图片缩放成指定尺寸(多余部分自动删除)
func scaled(to newSize: CGSize) -> UIImage {
//计算比例
let aspectWidth = newSize.width/size.width
let aspectHeight = newSize.height/size.height
let aspectRatio = max(aspectWidth, aspectHeight)
//图片绘制区域
var scaledImageRect = CGRect.zero
scaledImageRect.size.width = size.width * aspectRatio
scaledImageRect.size.height = size.height * aspectRatio
scaledImageRect.origin.x = 0
scaledImageRect.origin.y = 0
//绘制并获取最终图片
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)//图片不失真
draw(in: scaledImageRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
}
网友评论