0

我尝试从保存状态撤消 myContext 然后在我画线后我调用 undo 方法将我的上下文恢复到以前但它报告错误

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

1 回答 1

2

从我从您的问题中读到的内容,我猜您正在尝试实施撤消,对吗?CGContextSaveGStateCGContextRestoreGState此无关。

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

也就是说,您还引用了一个上下文已被销毁很长时间后的上下文。只要您调用UIGraphicsEndImageContext();,您之前存储在context变量中的上下文就消失了。这就是打印错误的原因。

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

于 2010-09-10T09:09:03.507 回答