How to crop the image using UIBezierPath?

Mani picture Mani · Oct 31, 2012 · Viewed 15.1k times · Source

I want to get the image from the UIBezierpath closed path(See the image). I draw the image on the UIView using drawRect method and also draw the lines are using the drawRect method. How can I get the particular closed path image? Please help me. Thanks in advance.

This code used for draw the bezierpath.

UIBezierPath *aPath = [UIBezierPath bezierPath];
for (NSString *pointString in pointArray) {
    if ([pointArray indexOfObject:pointString] == 0)
        [aPath moveToPoint:CGPointFromString(pointString)];
    else
        [aPath addLineToPoint:CGPointFromString(pointString)];
}
[aPath closePath];

enter image description here

Answer

iDev picture iDev · Nov 2, 2012

You can use a shapeLayer for that. Something like,

UIBezierPath *aPath = [UIBezierPath bezierPath];
for (NSString *pointString in pointArray) {
    if ([pointArray indexOfObject:pointString] == 0)
        [aPath moveToPoint:CGPointFromString(pointString)];
    else
        [aPath addLineToPoint:CGPointFromString(pointString)];
}
[aPath closePath];

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = aPath.CGPath;
[view.layer setMask:shapeLayer];//or make it as [imageview.layer setMask:shapeLayer]; 
//and add imageView as subview of whichever view you want. draw the original image
//on the imageview in that case

To get it as an image,

UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

image should have the corresponding image.