i want to crop image using any close path like UIB

2020-06-19 04:00发布

问题:

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.

回答1:

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.



回答2:

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



回答3:

// 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;}