2010-09-10 91 views
0

我尝试从保存状态 撤消myContext后,我再画我打电话撤消方法来我的上下文恢复到以前的行,但它报告错误时错误尝试复原上下文

<Error>: CGContextRestoreGState: invalid context 

代码

- (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); 
} 

回答

2

从我读到的问题来看,我猜你试图实现撤消,对吧? CGContextSaveGStateCGContextRestoreGState与此无关。

这两种方法只在上下文中存储上下文的元数据。像当前绘图颜色,坐标系统变换,线条粗细等元数据。您使用这些方法保存的GState允许您撤消上下文的设置,而不是内容。你必须以不同的方式进行撤销...

这就是说,你也可以在很长一段时间内销毁它之后引用它。只要您致电UIGraphicsEndImageContext();,您之前存储在context变量中的上下文就消失了。这就是打印错误的原因。

为了进行撤消操作,您可能必须存储您生成的图像或用户执行的操作或其他操作。 CGContexts不会帮你...

+0

谢谢Max Seelemann,你明白我的理解! – RAGOpoR 2010-09-10 09:33:14