Today we will learn how to crop an UIImage using iOS SDK. I tried various solution from the web but they are creating problem at some point. Finally i found a solution which work perfectly fine.
Crop:
In iOS core graphs provide a method to crop the image by providing the rect:
CGImageCreateWithImageInRect
So we will use this method to crop the image and main problem in cropping is scale is not maintained after crop the image and for that we need to scale the rect also for cropping.
Following is the solution for cropping the image with preserving the same scale:
- (UIImage*)cropImageWithSize:(CGSize)size ToRect:(CGRect)cropRect{
UIImage* cropImage = nil;
//Scale the rect to preserve the same scale. Self.Scale represent the image scale value
cropRect = CGRectMake(cropRect.origin.x * self.scale,
cropRect.origin.y * self.scale,
cropRect.size.width * self.scale,
cropRect.size.height * self.scale);
CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], cropRect);
cropImage = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
CGImageRelease(imageRef);
return cropImage;
}
So i have added this method in UIImage Category and use it.
Above method will crop the image if you have any UIImage and you have to provide the rect with respective of the image.
Example:
If my image size is 1024 * 768 then i can provide a rect
CGRectMake(0, 0, 1024, 384) and it will crop the upper half of image.
Comments
Post a Comment