'Swift: Image not cropping with .cropping(to: )
I am trying to crop an image and the output is the exact same as the input. I know where the issue is but I cannot figure out why it is not working.
Here is the func:
private func cropImage(image: CGImage, completion: @escaping (_ croppedImage: UIImage) -> Void) {
let imageScale: CGFloat = max(CGFloat(image.width) / 1080, CGFloat(image.height) / 1920)
print("imageScale: \(imageScale)")
let cropRect = CGRect(x: 0, y: 0, width: 1080, height: 1920)
print("cropRect: \(cropRect)")
let cropZone = CGRect(x: cropRect.origin.x * imageScale,
y: cropRect.origin.y * imageScale,
width: cropRect.width * imageScale,
height: cropRect.height * imageScale)
print("cropZone: \(cropZone)")
if let croppedImage: CGImage = image.cropping(to: cropZone) {
print("croppedImage: W\(croppedImage.width) H\(croppedImage.height)")
var image: UIImage = UIImage()
if self.currentDevicePosition == .front {
image = UIImage(cgImage: croppedImage, scale: 1.0, orientation: .leftMirrored)
} else {
image = UIImage(cgImage: croppedImage, scale: 1.0, orientation: .right)
}
print("uiimage scale: \(image.scale)")
print("uiimage size: \(image.size)")
completion(image)
}
}
Here are the print statements:
imageScale: 3.7333333333333334
cropRect: (0.0, 0.0, 1080.0, 1920.0)
cropZone: (0.0, 0.0, 4032.0, 7168.0)
croppedImage: W4032 H3024
uiimage scale: 1.0
uiimage size: (3024.0, 4032.0)
Based on what I am seeing from the print', it appears that everything is working correctly until "if let croppedImage: CGImage = image.cropping(to: cropZone)"
The cropZone is giving me a new ratio that is correct, but simply nothing changes to the image.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
