i want to crop image in my iPhone app using any close path like UIBezierPath. i know it is possible using rectangle but i want crop in different shape. like i make one shape using touch and want to crop that image so how it is possible. any suggestion or help. Thanks in advance.
Asked
Active
Viewed 3,261 times
5
-
1I never did before but I suppose you need to use mage masking. Try read this apple Doc [Quartz 2D Programming Guide](https://developer.apple.com/library/ios/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_images/dq_images.html#//apple_ref/doc/uid/TP30001066-CH212-CJBDIJEE). Maybe you could create a transparent image with bezierPath programmatically or by user interaction and then use this image as mask for your original image. – Gabriele Aug 18 '12 at 01:17
-
Masking is the way to got. Have a look at this short example http://mobiledevelopertips.com/cocoa/how-to-mask-an-image.html – mgratzer Aug 20 '12 at 06:08
3 Answers
2
You can crop your image with a shapelayer. To do it you have to create a path that will be used as borders for your new image. You should look at this question.
CALayer* contentLayer = [CALayer layer];
[contentLayer setFrame:CGRectMake(0, 0, 80, 80)];
CAShapeLayer* mask = [CAShapeLayer layer];
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL, 10, 10);
CGPathAddLineToPoint(path, NULL, 10, 80);
CGPathAddLineToPoint(path, NULL, 80, 80);
CGPathAddLineToPoint(path, NULL, 80, 10);
mask.path = path;
[contentLayer setContents:(id)[[UIImage imageNamed:@"image.png"] CGImage]];
[contentLayer setMask:mask];
[[self layer]addSublayer:contentLayer];
Something like this.

Community
- 1
- 1

Vitalii Boiarskyi
- 1,363
- 2
- 10
- 25
-
Vitaliy1 can you plz put the code here how to crop the image with shapelayer..... – Hardik Patel Apr 25 '13 at 05:20
1
you can accomplish this using a mask. you can create a mask using CGImageMaskCreate
.
if you need examples:
Any idea why this image masking code does not work?
http://mobiledevelopertips.com/cocoa/how-to-mask-an-image.html
0
// In Code Use:
-(UIImage *)croppedImage
{
UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.bezierPath closePath];
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 0.0);
_b_image = self.bg_imageview.image;
CGSize imageSize = _b_image.size;
CGRect imageRect = CGRectMake(0, 0, imageSize.width, imageSize.height);
UIGraphicsBeginImageContextWithOptions(imageSize, NO, [[UIScreen mainScreen] scale]);
[self.bezierPath addClip];
[_b_image drawInRect:imageRect];
UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return croppedImage;}

Ramani Hitesh
- 214
- 3
- 15