Goal: Crop a UIImage
(that starts with a scale
property of 2.0)
I perform the following code:
let croppedCGImage = originalUIImage.cgImage!.cropping(to: cropRect)
let croppedUIImage = UIImage(cgImage: croppedCGImage!)
This code works, however the result, croppedUIImage
, has an incorrect scale
property of 1.0.
I've tried specifying the scale
when creating the final image:
let croppedUIImage = UIImage(cgImage: croppedCGImage!, scale: 2.0, orientation: .up)
This yields the correct scale, but it cuts the size
dimensions in half incorrectly.
What should I do here?
(*Note: the scale
property on the UIImage is important because I later save the image with UIImagePNGRepresentation(_ image: UIImage)
which is affected by the scale
property)
Edit:
I got the following to work. Unfortunately it's just substantially slower than the CGImage
cropping function.
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
}
}