Search code examples
swiftuiimagecgrectcgimage

Swift cropping UIImage fails


I wrote the following function:

fileprivate func crop(image: UIImage, rect: CGRect) -> CGImage? {
        debugPrint("imageHeight: \(image.cgImage?.height)")
        debugPrint("imageWidth: \(image.cgImage?.width)")
        debugPrint("cropZone: \(rect)")

        guard let cropped = image.cgImage?.cropping(to: rect) else {
            debugPrint("cropping process failed")
            return nil
        }
        
        debugPrint("cropped")
        return cropped
    }

which gives me the output:

"imageHeight: Optional(4032)"
"imageWidth: Optional(3024)"
"cropZone: (3024.5166500171667, 1605.1421763895605, 949.3006961766132, 251.7156472208785)"
[Unknown process name] CGImageCreateWithImageProvider: invalid image size: 0 x 0.
"cropping process failed"

But I have no idea why the cropping process is failing.


Solution

  • The image is 3024 wide but the x coordinate for the cropping rectangle is 3024.5... which is outside of the image.