Iphone 在2个CGPath对象的交点外应用alpha

Iphone 在2个CGPath对象的交点外应用alpha,iphone,core-graphics,cgpath,Iphone,Core Graphics,Cgpath,我有一个奇形怪状多边形的CGPathRef。我需要在路径外的区域应用alpha。这很简单 CGContextAddPath(context, crazyPolygon); CGContextSetFillColor(context, someAlphaColor); CGContextEOFillPath(context); CGMutablePathRef circlePath = CGPathCreateMutable(); CGPathAddRect(circlePath, NULL,

我有一个奇形怪状多边形的CGPathRef。我需要在路径外的区域应用alpha。这很简单

CGContextAddPath(context, crazyPolygon);
CGContextSetFillColor(context, someAlphaColor);
CGContextEOFillPath(context);
CGMutablePathRef circlePath = CGPathCreateMutable();
CGPathAddRect(circlePath, NULL, rect);
CGPathAddEllipseInRect(circlePath, NULL, circleBox);
CGContextAddPath(context, circlePath);
CGContextSetFillColor(context, someAlphaColor);
CGContextEOFillPath(context);
我需要做一些类似的圆,也很简单

CGContextAddPath(context, crazyPolygon);
CGContextSetFillColor(context, someAlphaColor);
CGContextEOFillPath(context);
CGMutablePathRef circlePath = CGPathCreateMutable();
CGPathAddRect(circlePath, NULL, rect);
CGPathAddEllipseInRect(circlePath, NULL, circleBox);
CGContextAddPath(context, circlePath);
CGContextSetFillColor(context, someAlphaColor);
CGContextEOFillPath(context);
当我试图将这两个形状相交时,问题就出现了。我想将alpha应用于两个形状之外的任何像素

如果点位于圆中但不在多边形内,请应用alpha。 如果它在多边形中但不在圆中,则应用alpha。 如果它同时位于多边形和圆中,则像素应完全透明。
我试过很多不同的方法。没有一个奏效。最有希望的方法是使用多边形创建一个遮罩,并使用CGContextClipToMask绑定圆的图形。整个圆圈是在没有剪辑的情况下画出来的。

经过几个小时的反复尝试,我终于找到了答案

// Set up
CGContextRef context = UIGraphicsGetCurrentContext();
CGFloat outOfAreaColor[4] = { 0.0, 0.0, 0.0, OUT_OF_AREA_ALPHA };
CGContextSetFillColor(context, outOfAreaColor);

// Path for specifying outside of polygons
CGMutablePathRef outline = CGPathCreateMutable();
CGPathAddRect(outline, NULL, rect);
CGPathAddPath(outline, NULL, path);

// Fill the area outside of the path with an alpha mask
CGContextAddPath(context, outline);
CGPathRelease(outline);
CGContextEOFillPath(context);

// Add the inside path to the context and clip the context to that area
CGContextAddPath(context, insidePolygon);
CGContextClip(context);

// Create a path defining the area to draw outside of the circle
// but within the polygon
CGRect circleBox = CGRectMake(0, 0, circleRadius * 2.0, circleRadius * 2.0);
CGMutablePathRef darkLayer = CGPathCreateMutable();
CGPathAddRect(darkLayer, NULL, rect);
CGPathAddEllipseInRect(darkLayer, NULL, circleBox);
CGContextAddPath(context, darkLayer);
CGContextEOFillPath(context);
CGPathRelease(darkLayer);
使用cgpath addellipseinrect时,圆/椭圆的中心是circleBox.origin.x+circleBox.size.width/2.0、circleBox.origin.y+circleBox.size.height/2.0,而不是0.0、0.0。文档非常清楚地说明了这一点,但是在定位形状时必须弄清楚这一点很烦人