iPhone Developer Tips Visitor Stats: 126,691 Pageviews and 94,296 visitors in the past 30 days.
|
This post shows an example of one way to crop an image. Let’s begin by looking at a screenshot of the original and cropped image on the iPhone simulator:

As you can see, I am cropping a rectangle from the middle of the image on the top left. The code below shows how to accomplished this:
// Create the image from a png file
UIImage *image = [UIImage imageNamed:@"prgBinary.jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// Get size of current image
CGSize size = [image size];
// Frame location in view to show original image
[imageView setFrame:CGRectMake(0, 0, size.width, size.height)];
[[self view] addSubview:imageView];
[imageView release];
// Create rectangle that represents a cropped image
// from the middle of the existing image
CGRect rect = CGRectMake(size.width / 4, size.height / 4 ,
(size.width / 2), (size.height / 2));
// Create bitmap image from original image data,
// using rectangle to specify desired crop area
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *img = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
// Create and show the new image from bitmap data
imageView = [[UIImageView alloc] initWithImage:img];
[imageView setFrame:CGRectMake(0, 200, (size.width / 2), (size.height / 2))];
[[self view] addSubview:imageView];
[imageView release];
All the heavy lifting is done by the method CGImageCreateWithImageInRect, which creates a new bitmap image using existing image data and a rectangle that is a subregion of that same image. Once cropped, I create a new UIImageView and add it as a subview of the current view.
Share with iOS Developers:
Comments
5 Responses to “How to Crop an Image”
Leave Comment
Awesome, this totally rocks! Thanks
Nice job.
I used the “CGImageCreateWithImageInRect” to implement a Util to crop image.
Thank you, it helps a lot.
Great job. I was searching correct way of crop image. No memory leak.
Cheers
Thanks, this saved me time rummaging through all the CG library options!