目标:剪裁一个以2.0缩放属性开始的UIImage
。
我执行以下代码:
let croppedCGImage = originalUIImage.cgImage!.cropping(to: cropRect)
let croppedUIImage = UIImage(cgImage: croppedCGImage!)
这段代码可以运行,但是结果croppedUIImage
的scale
属性为错误的1.0。
我尝试在创建最终图像时指定scale
:
let croppedUIImage = UIImage(cgImage: croppedCGImage!, scale: 2.0, orientation: .up)
这会产生正确的比例,但会错误地将size
维度减半。
我该怎么做呢?
(*注:UIImage上的scale
属性很重要,因为我稍后使用UIImagePNGRepresentation(_ image: UIImage)
保存图像时会受到scale
属性的影响)
编辑:
我已经让以下内容工作了。不幸的是,它的速度比CGImage
裁剪函数慢得多。
extension UIImage {
func cropping(to rect: CGRect) -> UIImage {
UIGraphicsBeginImageContextWithOptions(rect.size, false, self.scale)
self.draw(in: CGRect(x: -rect.origin.x, y: -rect.origin.y, width: self.size.width, height: self.size.height))
let croppedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return croppedImage
}
}