有什么方法可以在我的图像中剪一个洞。我想要的是削减眼睛和嘴巴。我希望它变得透明。
答案 0 :(得分:6)
使UIBezierPath成为您想要透明的闭合路径的所有顶点。 bezier路径是这样的:
UIBezierPath *currentPath = [UIBezierPath bezierPath];
CGPoint tempPoint = CGPointMake(0,0);
[currentPath moveToPoint:CGPointMake(tempPoint.x, tempPoint.y)];
tempPoint = CGPointMake(0,20);
[currentPath addLineToPoint:CGPointMake(tempPoint.x, tempPoint.y)];
tempPoint = CGPointMake(20,20);
[currentPath addLineToPoint:CGPointMake(tempPoint.x, tempPoint.y)];
tempPoint = CGPointMake(20,0);
[currentPath addLineToPoint:CGPointMake(tempPoint.x, tempPoint.y)];
[currentPath closePath];
然后使用以下代码使该区域透明并保存在新图像中
// Create an image context containing the original UIImage.
UIGraphicsBeginImageContext(originalImage.size);
[originalImage drawAtPoint:CGPointZero];
// Clip to the bezier path and clear that portion of the image.
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddPath(context,currentPath.CGPath)
CGContextClip(context);
CGContextClearRect(context,CGRectMake(0,0,originalImage.size.width,originalImage.size.height);
// Build a new UIImage from the image context.
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
答案 1 :(得分:1)
尝试这个
首先添加quartzcore
#import <QuartzCore/QuartzCore.h>
创建要剪辑的路径
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRect:yourView.bounds];
[maskPath appendPath:[UIBezierPath bezierPathWithRect:rectToPunchThroughTheView]];
然后创建一个遮罩层并将其添加到您的视图中 - CAShapeLayer将允许您定义任何路径
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.fillRule = kCAFillRuleEvenOdd;
maskLayer.fillColor = [UIColor blackColor].CGColor;
maskLayer.path = maskPath.CGPath;
yourView.layer.mask = maskLayer;