Search code examples
iphoneobjective-ciosquartz-2d

remove clip on context in quartz 2d


I have drawn a path to my context with an arc, set that as a clip, and drawn an image into that clip.

CGContextBeginPath(context);
CGContextMoveToPoint(context, lineStartPoint.x, lineStartPoint.y);
CGContextAddArc(context, lineStartPoint.x, lineStartPoint.y, 105, toAngle*M_PI,fromAngle*M_PI , 1);
CGContextMoveToPoint(context, toLinePoint.x, toLinePoint.y);
CGContextClip(context);
[[UIImage imageNamed:@"gradientfill.png"] drawInRect:[self bounds]];

This works perfectly, as shown in this image

context clipping

My problem is that in the bottom of that gradient I have drawn a circle that I want to exist outside of the clip, it should look like this

enter image description here

How do I get my context to stop clipping so that I can have that circle outside of the clip?

My code for drawing the circle is

CGMutablePathRef path = CGPathCreateMutable();
CGRect toHandleRect = CGRectMake(toLinePoint.x-5, toLinePoint.y-5, 10, 10);    
CGPathAddEllipseInRect(path, NULL, toHandleRect);
CGContextAddPath(context, path);
CGPathRelease(path);

I want the user to be able to drag the little circle to anywhere in that view.


Solution

  • You can issue a CGContextSaveGState + CGContextRestoreGState pair as in the following example:

    // Saves the context including the current clipping region.
    CGContextSaveGState(context);
    
    // Build you clip region and do some drawing
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, lineStartPoint.x, lineStartPoint.y);
    CGContextAddArc(context, lineStartPoint.x, lineStartPoint.y, 105, toAngle*M_PI,fromAngle*M_PI , 1);
    CGContextMoveToPoint(context, toLinePoint.x, toLinePoint.y);
    CGContextClip(context);
    
    [[UIImage imageNamed:@"gradientfill.png"] drawInRect:[self bounds]];
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGRect toHandleRect = CGRectMake(toLinePoint.x-5, toLinePoint.y-5, 10, 10);    
    CGPathAddEllipseInRect(path, NULL, toHandleRect);
    CGContextAddPath(context, path);
    CGPathRelease(path);
    
    // Restore the original state
    CGContextRestoreGState(context);