When using .cropping(to: )
on a CGImage
the aspect ratio is not being respected.
As you can see the output cropped image height: 1080.0
should actually be 1350.0
Why is this crop not consistent with the defined rect?
These images are taken with the selfie camera in portrait orientation. I'm expecting all images taken from the selfie camera in portrait orientation to keep the original width but losing height when cropping. Crop will always be an aspect ratio of 4:5
let aspectRatio = CGFloat(4.0 / 5.0)
print("aspect ratio: \(aspectRatio)")
let rect = CGRect(
x: 0,
y: 0,
width: capture.size.width,
height: CGFloat(capture.size.width / aspectRatio)
)
image = crop(
image: capture,
toRect: rect
)
private func crop(image: UIImage, toRect rect: CGRect) -> UIImage? {
print("org image width: \(image.size.width)")
print("org image height: \(image.size.height)")
print("crop width: \(rect.size.width)")
print("crop height: \(rect.size.height)")
// Convert the UIImage to a CGImage
guard let cgImage = image.cgImage else { return nil }
// Apply the crop rect, adjusted for the image's scale
print("img scale: \(image.scale)")
print("rect x * scale: \(rect.origin.x * image.scale)")
print("rect y * scale: \(rect.origin.y * image.scale)")
print("rect width * scale: \(rect.size.width * image.scale)")
print("rect height * scale: \(rect.size.height * image.scale)")
let scaledRect = CGRect(
x: rect.origin.x * image.scale,
y: rect.origin.y * image.scale,
width: rect.size.width * image.scale,
height: rect.size.height * image.scale
)
guard let croppedCgImage = cgImage.cropping(to: scaledRect) else { return nil }
print("cropped cgimage width: \(croppedCgImage.width)")
print("cropped cgimage height: \(croppedCgImage.height)")
// Create a new UIImage from the cropped CGImage
let croppedImage = UIImage(cgImage: croppedCgImage, scale: image.scale, orientation: .leftMirrored)
print("cropped image width: \(croppedImage.size.width)")
print("cropped image height: \(croppedImage.size.height)")
return croppedImage
}
aspect ratio: 0.8
org image width: 1080.0
org image height: 1920.0
crop width: 1080.0
crop height: 1350.0
img scale: 1.0
rect x * scale: 0.0
rect y * scale: 0.0
rect width * scale: 1080.0
rect height * scale: 1350.0
cropped cgimage width: 1080
cropped cgimage height: 1080
cropped image width: 1080.0
cropped image height: 1080.0