Cropping a part of UIImage in iPhone

To crop any part of an image in iPhone using Objective C, start with an UIImage object.
   UIImage *image;

Create a bitmap representation the image using the CGImageRef class.
   CGImageRef imageReference = image.CGImage;

Define the frame size for the part of image which should be cropped.
   CGRect cropFrame = CGRectMake(10, 10, 50, 50);

Now set the current context of UIGraphics
   CGContextRef context = UIGraphicsGetCurrentContext();

Draw the image using the crop frame and imageReference using the current context.
   CGContextDrawImage(UIGraphicsGetCurrentContext(), cropFrame, imageReference);

Save the cropped image on a new UIImage object.
   UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();

After consolidating the above code to a single shot, it looks like,

   UIImage *image;
   CGImageRef imageReference = image.CGImage;
   CGRect cropFrame = CGRectMake(10, 10, 50, 50);
   CGContextRef context = UIGraphicsGetCurrentContext();
   CGContextDrawImage(UIGraphicsGetCurrentContext(), cropFrame, imageReference);
   UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();

And, ONE MORE THING,
At the end, for a better practice, always end the UIGraphicsContext.
    UIGraphicsEndImageContext();

Comments

Popular posts from this blog

Integrating ZXing QR Code reader in iPhone / iOS applications

Multiple line of text in UIPickerView

Connect Samsung devices to Kies on Mac