How to crop a UIImage without losing it's scale property?
<p>Goal: Crop a <code>UIImage</code> (that starts with a <code>scale</code> property of 2.0)</p>

<p>I perform the following code:</p>

<pre><code>let croppedCGImage = originalUIImage.cgImage!.cropping(to: cropRect)
let croppedUIImage = UIImage(cgImage: croppedCGImage!)
</code></pre>

<p>This code works, however the result, <code>croppedUIImage</code>, has an incorrect <code>scale</code> property of 1.0.</p>

<hr>

<p>I've tried specifying the <code>scale</code> when creating the final image:</p>

<pre><code>let croppedUIImage = UIImage(cgImage: croppedCGImage!, scale: 2.0, orientation: .up)
</code></pre>

<p>This yields the correct scale, but it cuts the <code>size</code> dimensions in half incorrectly.</p>

<hr>

<p>What should I do here?</p>

<p>(*Note: the <code>scale</code> property on the UIImage is important because I later save the image with <code>UIImagePNGRepresentation(_ image: UIImage)</code> which is affected by the <code>scale</code> property)</p>

<hr>

<hr>

<p>Edit:</p>

<p>I got the following to work.  Unfortunately it's just substantially slower than the <code>CGImage</code> cropping function.</p>

<pre><code>extension UIImage {
    func cropping(to rect: CGRect) -&gt; 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
    }
}
</code></pre>