使用给定路径剪切图像

时间:2016-01-05 08:47:21

标签: ios swift uiimage cgpath image-clipping

是否有基于给定路径(CGPath)剪辑图像块(UIImage)的标准方法? (路径是椭圆,星形,多边形......) 我目前的问题与此有关: AVCaptureStillImageOutput area selection 暂时没有得到答复,我仍然没有解决方案。

1 个答案:

答案 0 :(得分:0)

使用此代码

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();