CGImageCreateWithImageInRectincorrectly processes image orientation. There are many weird and wonderful cropping methods on the net that involve gigantic switch / case statements (see links in Ayaz's answer), but if you stay at the UIKit level and use only methods UIImageto do the drawing, all the caring details take care of you.
The following method is as simple as you can get and work in all the cases I came across:
- (UIImage *)imageByCropping:(UIImage *)image toRect:(CGRect)rect
{
if (UIGraphicsBeginImageContextWithOptions) {
UIGraphicsBeginImageContextWithOptions(rect.size,
NO,
0.0);
} else {
UIGraphicsBeginImageContext(rect.size);
}
[image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
You can change the value of the argument opaqueif you do not need transparency.
source
share