'Cropping image has incorrect x offset in swift
I have gotten the aspect ratio to be correct on the output, however the output oddly moves the cropped image positively on the x axis.
Preview:
Output:
Its a really odd thing to happen, and I am not sure exactly whats causing this result. Why is the x offset incorrect?
Heres the code:
private func cropImage(image: CGImage, completion: @escaping (_ croppedImage: UIImage) -> Void) {
let aspectRatio: CGFloat = 2208 / 1170
let cropRect = CGRect(x: 0, y: 0, width: CGFloat(image.width), height: CGFloat(image.width) / aspectRatio)
if let croppedImage: CGImage = image.cropping(to: cropRect) {
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 size: \(image.size)")
completion(image)
}
}
Solution 1:[1]
This is what I ended up with. Yes the aspect ratio is different but it does not affect my original question. I was able to fix the x offset within the cropRect. Notice how I changed the "y" in the cgrect? This is because the image is rotated after the crop, reversing many factors to the image. Anyways, this is not an elegant solution by any means. Most of it is also hard coded, which is fine for my use since these numbers will actually never need to change. But nonetheless, I am still searching for a better solution.
private func cropImage(image: CGImage, completion: @escaping (_ croppedImage: UIImage) -> Void) {
let aspectRatio: CGFloat = 1920 / 1080
let cropRectY: CGFloat = ((1920 - 1080) / aspectRatio) - 100
let cropRect = CGRect(x: 0, y: cropRectY, width: CGFloat(image.width), height: CGFloat(image.width) / aspectRatio)
if let croppedImage: CGImage = image.cropping(to: cropRect) {
var uiImage: UIImage = UIImage()
if self.currentDevicePosition == .front {
uiImage = UIImage(cgImage: croppedImage, scale: 1.0, orientation: .leftMirrored)
} else {
uiImage = UIImage(cgImage: croppedImage, scale: 1.0, orientation: .right)
}
completion(uiImage)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Trevor |


