查看本答案https://stackoverflow.com/a/15228510/1717391。 您可以將rects添加到CGMutablePathRef,而不是將它們添加到NSMutableArray。
// helper function, returns the area between rect1 and rect2 along the edge
static CGRect rectBetween(CGRect rect1, CGRect rect2, CGRect* remainder, CGRectEdge edge)
{
CGRect intersectedRect = CGRectIntersection(rect1, rect2);
if (CGRectIsEmpty(intersectedRect)) {
return CGRectNull;
}
CGRect rect3;
float chopAmount = 0;
switch (edge) {
case CGRectMaxYEdge:
chopAmount = rect1.size.height - (intersectedRect.origin.y - rect1.origin.y);
if (chopAmount > rect1.size.height) { chopAmount = rect1.size.height; }
break;
case CGRectMinYEdge:
chopAmount = rect1.size.height - (CGRectGetMaxY(rect1) - CGRectGetMaxY(intersectedRect));
if (chopAmount > rect1.size.height) { chopAmount = rect1.size.height; }
break;
case CGRectMaxXEdge:
chopAmount = rect1.size.width - (intersectedRect.origin.x - rect1.origin.x);
if (chopAmount > rect1.size.width) { chopAmount = rect1.size.width; }
break;
case CGRectMinXEdge:
chopAmount = rect1.size.width - (CGRectGetMaxX(rect1) - CGRectGetMaxX(intersectedRect));
if (chopAmount > rect1.size.width) { chopAmount = rect1.size.width; }
break;
default:
break;
}
CGRectDivide(rect1, remainder, &rect3, chopAmount, edge);
return rect3;
}
/**
* create a path by substracting rect2 from rect1.
* return NULL if rect1 is empty.
* Caller have to released the resulting path
*/
-(CGPathRef)createPathFromRect:(CGRect)rect1 clippingRect:(CGRect)rect2
{
if (CGRectIsEmpty(rect1)) {
return NULL;
}
CGMutablePathRef path = CGPathCreateMutable();
CGRect intersectedRect = CGRectIntersection(rect1, rect2);
// No intersection
if (CGRectIsEmpty(intersectedRect)) {
CGPathAddRect(path, NULL, rect1);
return path;
}
CGRect remainder;
CGRect subtractedArea;
subtractedArea = rectBetween(rect1, intersectedRect, &remainder, CGRectMaxYEdge);
if (!CGRectIsEmpty(subtractedArea)) {
CGPathAddRect(path, NULL, subtractedArea);
}
subtractedArea = rectBetween(remainder, intersectedRect, &remainder, CGRectMinYEdge);
if (!CGRectIsEmpty(subtractedArea)) {
CGPathAddRect(path, NULL, subtractedArea);
}
subtractedArea = rectBetween(remainder, intersectedRect, &remainder, CGRectMaxXEdge);
if (!CGRectIsEmpty(subtractedArea)) {
CGPathAddRect(path, NULL, subtractedArea);
}
subtractedArea = rectBetween(remainder, intersectedRect, &remainder, CGRectMinXEdge);
if (!CGRectIsEmpty(subtractedArea)) {
CGPathAddRect(path, NULL, subtractedArea);
}
return path;
}
- (void)drawRect:(CGRect)rect
{
CGPathRef path = [self createPathFromRect:CGRectMake(10, 10, 200, 200) clippingRect:CGRectMake(210-40, 10, 40, 40)];
if (path)
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddPath(ctx, path);
CGContextFillPath(ctx);
CFRelease(path);
}
}