Here is a code for cropping image on iPhone.
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches]anyObject];
CGPoint loc = [touch locationInView:touch.view];
tmpVView.frame = CGRectMake(tmpVView.frame.origin.x, tmpVView.frame.origin.y, fabs(tmpVView.frame.origin.x-loc.x), fabs(tmpVView.frame.origin.y-loc.y));
}
-(void)cropImage:(id)sender
{
if(tmpVView && tmpVView.frame.size.width > 10 && tmpVView.frame.size.height > 10)
{
//UIImage *img = [originalImg.image imageScaledToSize:CGSizeMake(32.0f, 32.0f) interpolationQuality:1];
//UIImage *img = [self resizedImage:originalImg.image inFrame:originalImg.frame];
[originalImg drawRect:originalImg.frame];
finalImg.image = [self imageByCropping:originalImg.image toRect:tmpVView.frame];
[tmpVView removeFromSuperview];
[tmpVView release];
tmpVView = nil;
}
}
- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
//create a context to do our clipping in
UIGraphicsBeginImageContext(rect.size);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
//create a rect with the size we want to crop the image to
//the X and Y here are zero so we start at the beginning of our
//newly created context
CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
CGContextClipToRect( currentContext, clippedRect);
//create a rect equivalent to the full size of the image
//offset the rect by the X and Y we want to start the crop
//from in order to cut off anything before them
CGRect drawRect = CGRectMake(rect.origin.x * -1,
rect.origin.y * -1,
imageToCrop.size.width,
imageToCrop.size.height);
CGContextTranslateCTM(currentContext, 0.0, drawRect.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
//draw the image to our clipped context using our offset rect
CGContextDrawImage(currentContext, drawRect, imageToCrop.CGImage);
//pull the image from our cropped context
UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();
//pop the context to get back to the default
UIGraphicsEndImageContext();
//Note: this is autoreleased
return cropped;
}
Enjoy!
3 comments:
Hello. And Bye.
What is tempVView?
"tempVView" is a temporary view, which I drawn over the image. When done drawing rectangle over the image using this "tempVView" and crop clicked, the image that comes under tempVView, gets cropped and re-sized.
Post a Comment
Tweet