Iphone 用CoreGraphics绘图

Iphone 用CoreGraphics绘图,iphone,core-graphics,undo,Iphone,Core Graphics,Undo,我正在使用CoreGraphics来实现徒手绘制,这对我来说很好,现在我想为这个绘制实现撤销功能,以便用户可以清除他的最后一个笔划 这是我的画法,使用了UITouchesBegin和UITouchesMoved -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [touches anyObject]; previousPoint2 = previousPoint

我正在使用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];
}

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

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

  • 你可以得到一个离线缓冲区画布,在这里你可以在绘制点时创建一个图像,每次绘制时更新它。在这里,您还需要创建一个点数组,但不需要每次都重新绘制。执行撤消操作时,只需删除最后一个对象并在阵列中绘制点时创建一个新的缓冲区画布


  • 我试着使用有问题的代码,但没有成功。谢谢酒窝,第一个选择让我印象深刻,但如果你能为我详细说明一下,我还添加了UITouchesMoved方法。