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.
Asked
Active
Viewed 484 times
1 Answers
0
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();

Aruna Mudnoor
- 4,795
- 14
- 16
-
Thanks! I am trying to use this nice code, facing some issues though. The resulting image is oriented the wrong way and there are scaling problems, the mask being shrinked. I had to fix a few details, but I think the basic idea is good and I'd like to make it work. – Michel Jan 06 '16 at 04:48
-
Yes you are right. You have to consider the orientation and scaling factor. – Aruna Mudnoor Jan 07 '16 at 07:24
-
Yes, it appears more difficult than I first thought. I have more or less solved the clipping aspect, but I have problems to save the different clips as PNG file the way I would like. Actually I even made a special app for testing this side of thing, with a post to ask for help: http://stackoverflow.com/questions/34646982/avcapturestillimageoutput-uiimagepngrepresentation – Michel Jan 07 '16 at 07:40
-
This may help you http://stackoverflow.com/questions/7645454/resize-uiimage-by-keeping-aspect-ratio-and-width – Aruna Mudnoor Jan 07 '16 at 09:15
-
The Swift answer shows how to clip using a UIBezierPath and get an image with an alpha channel in PNG format. It also show how to save the clip to the camera roll and how to place it into the pasteboard. https://stackoverflow.com/questions/49853122/swift-clipping-image-with-uibezierpath/65533953#65533953 – user3408691 Jan 01 '21 at 22:01