Michel
Michel

Reputation: 11755

Clipping an image with a given path

Is there a standard way to clip a chunk of an image(UIImage) based on a given path(CGPath) ? (The path being an ellipse, a star, a polygon …) My present question is related to this one: AVCaptureStillImageOutput area selection which has been unanswered for the time being and for which I still have no solution.

Upvotes: 0

Views: 517

Answers (1)

Aruna Mudnoor
Aruna Mudnoor

Reputation: 4825

Use this code

CGPathRef path = CGPathCreateWithEllipseInRect(CGRectMake(50.0,50.0,300.0,200.0), nil);

UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [UIColor blackColor].CGColor);
CGContextAddPath(UIGraphicsGetCurrentContext(), path);
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [UIColor redColor].CGColor);
CGContextDrawPath(UIGraphicsGetCurrentContext(), kCGPathFillStroke);
UIImage *maskImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImage *originalImage = [UIImage imageNamed:@"image"];
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextClipToMask(UIGraphicsGetCurrentContext(), CGRectMake(0.0,0.0,300.0,200.0), maskImage.CGImage);
[captureImage drawAtPoint:CGPointZero];
UIImage *clippedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Upvotes: 0

Related Questions