read

I recently had to write some code to use the UIImagePickerControllerCropRect when picking or taking a photo. Looking around the web there were some pretty crazy coding examples that seemed to be unnecessarily complicated so I knocked up my own quick solution.

// ger the original image along with it's size
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
CGSize size = image.size;
    
// crop the crop rect that the user selected
CGRect cropRect = [[info objectForKey:UIImagePickerControllerCropRect] 
                  CGRectValue];

// create a graphics context of the correct size    
UIGraphicsBeginImageContext(cropRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();

// correct for image orientation    
UIImageOrientation orientation = [image imageOrientation];
if(orientation == UIImageOrientationUp) {
  CGContextTranslateCTM(context, 0, size.height);
  CGContextScaleCTM(context, 1, -1);                
  cropRect = CGRectMake(cropRect.origin.x, 
                        -cropRect.origin.y, 
                        cropRect.size.width, 
                        cropRect.size.height);
} else if(orientation == UIImageOrientationRight) {
  CGContextScaleCTM(context, 1.0, -1.0);
  CGContextRotateCTM(context, -M_PI/2);
  size = CGSizeMake(size.height, size.width);
  cropRect = CGRectMake(cropRect.origin.y, 
                        cropRect.origin.x, 
                        cropRect.size.height, 
                        cropRect.size.width);
} else if(orientation == UIImageOrientationDown) {
  CGContextTranslateCTM(context, size.width, 0);
  CGContextScaleCTM(context, -1, 1);        
  cropRect = CGRectMake(-cropRect.origin.x, 
                        cropRect.origin.y, 
                        cropRect.size.width, 
                        cropRect.size.height);
}
// draw the image in the correct place
CGContextTranslateCTM(context, -cropRect.origin.x, -cropRect.origin.y);
CGContextDrawImage(context, 
                   CGRectMake(0,0, size.width, size.height), 
                   image.CGImage);
// and pull out the cropped image
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Why not subscribe to my mailing list - I'll send out regular emails with new content (don't worry I won't spam you!)

* indicates required
Blog Logo

Chris Greening


Published

Image

Chris Greening

Blogging about random stuff

Back to Overview