Reputation: 1310
- (UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
I am Using this code. Please give some solutions.Thanks in advance
Upvotes: 5
Views: 1636
Reputation: 45598
CGImageCreateWithImageInRect
does not handle image orientation correctly.
There are many strange and wonderful cropping techniques out there on the net involving giant switch/case statements (see the links in Ayaz's answer), but if you stay at the UIKit-level and use only methods on UIImage
itself to do the drawing, all the nitty gritty details are taken care for you.
The following method is as simple as you can get and works in all cases that I have encountered:
- (UIImage *)imageByCropping:(UIImage *)image toRect:(CGRect)rect
{
if (UIGraphicsBeginImageContextWithOptions) {
UIGraphicsBeginImageContextWithOptions(rect.size,
/* opaque */ NO,
/* scaling factor */ 0.0);
} else {
UIGraphicsBeginImageContext(rect.size);
}
// stick to methods on UIImage so that orientation etc. are automatically
// dealt with for us
[image drawAtPoint:CGPointMake(-rect.origin.x, -rect.origin.y)];
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
You may want to change the value of the opaque
argument if you don't need transparency.
Upvotes: 4