0

我知道这种帖子被问了很多时间,但我在谷歌和这个网站上搜索了很多,没有找到任何解决方案,这就是我发布这个问题的原因。我想撤消我绘制的 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;}

谢谢。

4

2 回答 2

1

要添加撤消:

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

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

于 2013-02-07T13:59:10.917 回答
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];
}
于 2013-02-07T13:57:44.260 回答