简体   繁体   中英

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;

     }

}

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

Clear All CGContextRef Drawings:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, self.bounds); //self.bounds = your drawing base frame
[self setNeedsDisplay];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM