2010-09-10 33 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