I would like to create a new UIImage by cropping the image inside a UIImageView. For example in the above pic, I want a new UIImage of the area outlined in green. I found code to do this, normally it looks something like this (as a UIImage category):
- (UIImage *)croppedImage:(CGRect)bounds {
CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], bounds);
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return croppedImage;
}
Makes perfect sense. HOWEVER, my UIImageView is in contentMode 'aspect fit'. Seems like that complicates the CGRect calculations for CGImageCreateWithImageInRect and I haven't been able to figure out the right solution.
I figure I need to apply the same transformations to the green rect as were done to the image?
ALSO: I found this other question here (How to know the image size after applying aspect fit for the image in an UIImageView), which seems to show a brute force way of getting the size, but I am still not sure how that fits into a cropping situation.
Any ideas?
EDIT: In my case, I literally have a square as shown above drawn in an overlay view over the UIImageView. So while I realize I am cropping the UIImage (inside the UIImageView), I need to somehow change the green CGRect such that it 'matches' the transformation done when 'aspect fit' is applied. For example, if I leave my UIImageView in 'top left' mode, then everything works fine, because there is a 1:1 mapping between the underlying UIImage and the UIImageView. The problem in 'top left' mode is that the entire image doesn't always display, because it might be bigger than my UIImageView.