I'm having a hell of a time using CGImageCreateWithImageInRect to crop a photo. My app has the user move / enlarge an image till it fills a 316 x 316 view, then I want it to crop off any area outside the box and save the image as a UIImage. I determine the crop origin by taking the absolute value of the x and y imageview origin as that brings me back to 0,0 of the view / box that contains the imageview. Below is the code:
CGRect croppedRect = CGRectMake(fabs(widthDistanceToOrigin), fabs(HeightDistanceToOrigin), 316, 316);
CGImageRef croppedImageRef = CGImageCreateWithImageInRect(image.CGImage, croppedRect);
UIImage *croppedImage = [UIImage imageWithCGImage: croppedImageRef scale: 1 / (imageScale) orientation: image.imageOrientation];
CGImageRelease(croppedImageRef);
This is driving me crazy, I just can't get it to crop the area I want. I've got it to scale correctly, but the problem seems to be with the x and y origin of the crop rect, it's quite a bit off from the area it should be taking (and sometimes I get weird results).
Also, it seems for images taken with the phones camera, I have to multiply everything in my crop rect by 2 for it to be the correct size. Very weird.
So I'm wondering, does anyone know how to fix this, or does anyone possible have a better way of cropping (and please keep in mind that I need to crop an area within my photo). Thanks!
I found the problem. I was trying to grab the crop area before I scaled the image. Now have to figure out how to reduce the image before I do "CGImageCreateWithImageInRect".
I would like to provide more information/answer for this based on my own experience.
From the
UIImage
(and thus theCGImageCreateWithImageInRect:
) perspective,(0, 0)
is in the bottom left. When determining the crop square, you can simply calculate the square based on the standard portrait orientation and then use the method in @greenhouse's answer (posted again here for clarity and changed to useCGFloat
to fix a casting error.This code shifts the crop square so that it is in the correct relative position.
There are so many posts about this topic with all them having the same exact answer, to utilize: CGImageCreateWithImageInRect but none of them fully solve the problem of miss positioning of what is trying to be cropped.
However, only one thread (buried deep deep inside), has a minor detail that everyone else is missing... How to crop a UIImageView to a new UIImage in 'aspect fit' mode?
the 'rect' parameter that goes in CGImageCreateWithImageInRect(image.CGImage, croppedRect) needs to represent (taken from) the UIImage, NOT the UIImageView.
this should solve the issue of miss positioning on the coordinate system.