iphoneiosuikitcore-graphicscgcontextref

How to clear a CGContextRef?


I experimenting with creating a simple finger-painting application on the ipad. I am able to draw a path to the screen correctly, but I want to have an option that completely clears the screen of all drawn paths. The code I currently have clears the context, but when I call the drawing code block all the paths reappear on screen.

- (void)drawRect:(CGRect)rect
{
   //Drawing code
   CGContextRef context = UIGraphicsGetCurrentContext();

     if(clearContext == 0){

        CGContextSetLineWidth(context, 6);
        CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
        CGContextAddPath(context, drawingPath);

        CGContextStrokePath(context);
     }
     if(clearContext == 1){

      //This is the code I currently have to clear the context, it is clearly wrong
      //Just used as experimentation.

      CGContextSetBlendMode(context, kCGBlendModeClear);
      CGContextAddPath(context, drawingPath);
      CGContextStrokePath(context);
      clearContext = 0;

     }

}

Solution

  • im assuming drawingPath is a CGPath ... are you clearing that CGPath? that might be the cause of your problem

    in the action to clear your path, do:

    CGPathRelease(drawingPath);
    drawingPath = CGPathCreateMutable();
    [self setNeedsDisplay];
    

    and do the normal drawing you usually do. if the path is empty, nothing will be drawn