read
Want to keep up to date with the latest posts and videos? Subscribe to the newsletter
HELP SUPPORT MY WORK: If you're feeling flush then please stop by Patreon Or you can make a one off donation via ko-fi
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();
Related Posts
Related Videos
Want to keep up to date with the latest posts and videos? Subscribe to the newsletter