views:

15

answers:

1

i try to undo myContext from save state then after i draw the line i call undo method to restore my context to previous but it report error

<Error>: CGContextRestoreGState: invalid context

code

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];   
    CGPoint currentPoint = [touch locationInView:self.view];
    UIGraphicsBeginImageContext(self.view.frame.size);
    [drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();    
}

- (void)undo {
    CGContextRestoreGState(context);
}
+1  A: 

From what I read from you question, I guess that you're trying to implement undo, right? CGContextSaveGState and CGContextRestoreGState have nothing to do with that.

These two methods only store meta-data of the context in the context. Metadata like the current drawing color, coordinate-system transformation, line thickness etc. This GState you preserve using these methods allows you to undo settings of a context, not it's content. You have to do undo in a different way...

That said, you also refer to a context after it has been destroyed for a long time. As soon as you call UIGraphicsEndImageContext();, the context you previously stored in the context variable is gone. And that's the reason why the error is being printed.

In order to do undo, you'd probably have to store the image you generated or the actions the user did or something else. CGContexts won't help you there...

Max Seelemann
Thank Max Seelemann, you give me understand clearly!
RAGOpoR