应用2个CGPath对象的alpha外部交叉点

时间:2011-08-10 18:12:43

标签: iphone core-graphics cgpath

我有一个奇怪形状的多边形CGPathRef。我需要将alpha应用于此路径的 outside 区域。这非常简单。

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来限制圆的绘制。虽然画了整个圆圈但没有剪裁。

1 个答案:

答案 0 :(得分:0)

经过几个小时的反复试验后,我终于明白了。

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

使用CGPathAddEllipseInRect时,圆圈/椭圆的中心为circleBox.origin.x + circleBox.size.width / 2.0, circleBox.origin.y + circleBox.size.height / 2.0,而不是0.0, 0.0。文档使这一点非常清楚,但是在定位形状时必须弄明白这一点很烦人。