Cropping an UIImage Cropping an UIImage ios ios

Cropping an UIImage


Update 2014-05-28: I wrote this when iOS 3 or so was the hot new thing, I'm certain there are better ways to do this by now, possibly built-in. As many people have mentioned, this method doesn't take rotation into account; read some additional answers and spread some upvote love around to keep the responses to this question helpful for everyone.

Original response:

I'm going to copy/paste my response to the same question elsewhere:

There isn't a simple class method to do this, but there is a function that you can use to get the desired results: CGImageCreateWithImageInRect(CGImageRef, CGRect) will help you out.

Here's a short example using it:

CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);// or use the UIImage wherever you like[UIImageView setImage:[UIImage imageWithCGImage:imageRef]]; CGImageRelease(imageRef);


To crop retina images while keeping the same scale and orientation, use the following method in a UIImage category (iOS 4.0 and above):

- (UIImage *)crop:(CGRect)rect {    if (self.scale > 1.0f) {        rect = CGRectMake(rect.origin.x * self.scale,                          rect.origin.y * self.scale,                          rect.size.width * self.scale,                          rect.size.height * self.scale);    }    CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);    UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];    CGImageRelease(imageRef);    return result;}


You can make a UIImage category and use it wherever you need. Based on HitScans response and comments bellow it.

@implementation UIImage (Crop)- (UIImage *)crop:(CGRect)rect {    rect = CGRectMake(rect.origin.x*self.scale,                       rect.origin.y*self.scale,                       rect.size.width*self.scale,                       rect.size.height*self.scale);           CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);    UIImage *result = [UIImage imageWithCGImage:imageRef                                           scale:self.scale                                     orientation:self.imageOrientation];     CGImageRelease(imageRef);    return result;}@end

You can use it this way:

UIImage *imageToCrop = <yourImageToCrop>;CGRect cropRect = <areaYouWantToCrop>;   //for example//CGRectMake(0, 40, 320, 100);UIImage *croppedImage = [imageToCrop crop:cropRect];