1

我正在使用 CoreGraphics 实现自由手绘,这对我来说效果很好,现在我想为此绘图实现撤消功能,以便用户可以清除他的最后一笔。

这是我使用 UITouchesBegin 和 UITouchesMoved 的绘图方法。

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

    previousPoint2  = previousPoint1;
    previousPoint1  = [touch previousLocationInView:self];
    currentPoint    = [touch locationInView:self];


    // calculate mid point
    CGPoint mid1    = midPoint(previousPoint1, previousPoint2);
    CGPoint mid2    = midPoint(currentPoint, previousPoint1);

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, mid1.x, mid1.y);
    CGPathAddQuadCurveToPoint(path, NULL, previousPoint1.x, previousPoint1.y, mid2.x, mid2.y);
    CGRect bounds = CGPathGetBoundingBox(path);
    CGPathRelease(path);

    drawBox = bounds;

    //Pad our values so the bounding box respects our line width
    drawBox.origin.x        -= self.lineWidth * 2;
    drawBox.origin.y        -= self.lineWidth * 2;
    drawBox.size.width      += self.lineWidth * 4;
    drawBox.size.height     += self.lineWidth * 4;

    UIGraphicsBeginImageContext(drawBox.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    curImage = UIGraphicsGetImageFromCurrentImageContext();
    [curImage retain];
    UIGraphicsEndImageContext();

    [self setNeedsDisplayInRect:drawBox];
}

-(void)drawRect:(CGRect)rect {
    [curImage drawAtPoint:CGPointMake(0, 0)];
    CGPoint mid1 = midPoint(previousPoint1, previousPoint2);
    CGPoint mid2 = midPoint(currentPoint, previousPoint1);

    context = UIGraphicsGetCurrentContext();

    [self.layer renderInContext:context];

    CGContextMoveToPoint(context, mid1.x, mid1.y);
    // Use QuadCurve is the key
    CGContextAddQuadCurveToPoint(context, previousPoint1.x, previousPoint1.y, mid2.x, mid2.y);

    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineWidth(context, self.lineWidth);
    CGContextSetStrokeColorWithColor(context, self.lineColor.CGColor);

    CGContextStrokePath(context);

    [super drawRect:rect];
}
4

1 回答 1

2

在我看来,有两种方法可以实现这一点

  1. 您可以在 NSArray 中保存路径并在调用drawRect方法时在循环中绘制所有路径,然后在撤消时删除最后一个对象,将其添加到缓冲区数组并重绘所有数组。

  2. 您可以获得一个离线缓冲区画布,您可以在其中绘制点时创建图像,每次绘制时更新它。在这里,您还需要创建一个点数组,但不是每次都重绘。当您撤消时,只需删除最后一个对象并在数组中绘制点时创建一个新的缓冲区画布。

于 2012-04-09T11:34:01.500 回答