撤消CGContext行

时间:2013-02-07 13:36:48

标签: iphone objective-c draw cgcontext undo

我知道这种帖子被问了很多时间,但我在谷歌和这个网站上搜索了很多,没有找到任何解决方案,这就是我发布这个问题的原因。我想撤消我绘制的CGContext行,而不使用UIBezierPath或其他任何东西。有办法吗?这是我用来绘制的代码:

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

UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:mainImageView];

UIGraphicsBeginImageContext(mainImageView.frame.size);
[mainImageView.image drawInRect:CGRectMake(0, 0, mainImageView.frame.size.width, mainImageView.frame.size.height)];

CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), dimension);

const CGFloat *components = CGColorGetComponents([color CGColor]);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), components[0], components[1], components[2], components[3]);

CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());

mainImageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

lastPoint = currentPoint;}

感谢。

2 个答案:

答案 0 :(得分:0)

由于您正在绘制图像,因此您可以将图像置零,并且可见线将消失。

mainImageView.image = NULL;
// Or
mainImageView.image = originalImage; // Where originalImage is your background if you're using one.

<强>更新

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:mainImageView];

    UIGraphicsBeginImageContext(mainImageView.frame.size);

    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), dimension);

    const CGFloat *components = CGColorGetComponents([color CGColor]);
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), components[0], components[1], components[2], components[3]);

    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());

    // Add the line as a subView.
    [mainImageView addSubView:[[UIImageView alloc] initWithImage:UIGraphicsGetImageFromCurrentImageContext()]];
    UIGraphicsEndImageContext();

    lastPoint = currentPoint;

}

- (void)undoLastLine
{
    [mainImageView.subviews.lastObject removeFromSuperview];
}

答案 1 :(得分:0)

添加撤消:

一旦图像被覆盖,您就无法在图像中显示任何信息......

每次更改时,您都必须保留图像的副本(大量内存,尽管可以通过仅保留更改区域的副本来减少这些内容),或者记录用户的绘图步骤和然后在撤消后重播它们。