There are so many posts on this topic, all of them have the same exact answer, use: CGImageCreateWithImageInRect but none of them completely solve the problem of missing positioning of what it is trying to crop.
However, only one thread (deeply immersed deep in depth) has an insignificant detail that everyone else lacks ... How to crop a UIImageView into a new UIImage mode in aspect matching mode?
the 'rect' parameter, which is included in CGImageCreateWithImageInRect (image.CGImage, croppedRect) should represent (taken from) UIImage, not UIImageView.
this should solve the problem of positioning gaps in the coordinate system.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo: (NSDictionary *)info { oImage = [info valueForKey:UIImagePickerControllerOriginalImage]; NSLog(@"Original Image size width: %fx height: %f", oImage.size.width, oImage.size.height); // crop image according to what the image picker view is displaying CGRect rect = CGRectMake(0, 40, 960.0f, 960.0f); // note: 960 x 1280 is what natively comes from capturing and image nImage = [BGViewModifiers cropImage:oImage inRect:rect]; // scale image down for display and creating kombie CGSize size = CGSizeMake(320.0f, 320.0f); nImage = [BGViewModifiers imageFromImage:nImage scaledToSize:size]; NSLog(@"New Image size width: %fx height: %f", [nImage size].width, [nImage size].height); } //ref: http://stackoverflow.com/a/25293588/2298002 + (UIImage *)cropImage:(UIImage*)image inRect:(CGRect)rect { double (^rad)(double) = ^(double deg) { return deg / 180.0 * M_PI; }; CGAffineTransform rectTransform; switch (image.imageOrientation) { case UIImageOrientationLeft: rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -image.size.height); break; case UIImageOrientationRight: rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -image.size.width, 0); break; case UIImageOrientationDown: rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -image.size.width, -image.size.height); break; default: rectTransform = CGAffineTransformIdentity; }; rectTransform = CGAffineTransformScale(rectTransform, image.scale, image.scale); CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectApplyAffineTransform(rect, rectTransform)); UIImage *result = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation]; CGImageRelease(imageRef); return result; } + (UIImage*)imageFromImage:(UIImage*)image scaledToSize:(CGSize)newSize { UIGraphicsBeginImageContext( newSize ); [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage; }
source share