iphone:如何通过自由手绘制时重做/撤消

时间:2012-03-08 07:23:16

标签: iphone cgcontext uitouch

实际上我通过自由手绘制图像的样本很少,我也在我的应用程序中集成了。我需要其他功能,例如undo / redo。我可以实现这个吗?需要帮助...我使用下面的代码。

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    mouseSwiped = YES;

    UITouch *touch = [touches anyObject];   
    CGPoint currentPoint = [touch locationInView:self.view];
    currentPoint.y -= 20;


    UIGraphicsBeginImageContext(self.view.frame.size);
    [drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 10.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();

    lastPoint = currentPoint;

    mouseMoved++;

    if (mouseMoved == 10) {
        mouseMoved = 0;
    }
}

2 个答案:

答案 0 :(得分:5)

    CGMutablePathRef path;
    path = CGPathCreateMutable();
    - (void)drawRect:(CGRect)rect
    {
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGPathMoveToPoint(path, NULL, previousPoint.x, previousPoint.y);
    CGPathAddLineToPoint(path, NULL, lastPoint.x, lastPoint.y);
    CGContextAddPath(context, path);

    CGContextSetLineWidth(context, 10.0);
[[UIColor greenColor] setStroke];
    CGContextDrawPath(context,kCGPathFillStroke);
    }

现在您可以按路径索引执行撤消/重做。

答案 1 :(得分:2)

您可以尝试将所有路径存储在数组中。 当你绘制一个新的,最后添加并绘制它,当你删除 - 删除最后一个并重绘所有。保留在另一个数组中删除,以便您可以重做操作,在将新路径添加到路径数组时清除重做数组。 这是我能想到的最直接的方法。