2012-04-09 82 views
1

我正在使用CoreGraphics來實現對我來說工作正常的自由手繪圖,現在我想爲此繪圖實現撤消功能,以便用戶可以清除其最後一個筆畫。使用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]; 
} 
+0

http://stackoverflow.com/questions/5741880/iphone-paint-application – 2012-04-09 10:49:59

+0

我試圖在問題的代碼,但不能這樣做成功。 [Here](http://stackoverflow.com/questions/6689600/undo-drawing-in-paint-application) – 2012-04-09 10:50:58

回答

2

有可能實現這種對我的觀點2種方式

  1. U可以在NSArray的保存路徑,並繪製所有環路的同時,調用drawRect方法,然後同時撤消,除去最後對象,將其添加到緩衝區數組並重新繪製所有數組。

  2. U可以獲得一個離線緩衝區畫布,您可以在繪製點時創建圖像,每次繪製時更新它。這裏還需要創建一個點數組,但不是每次重繪。當你撤銷時,只需刪除最後一個對象,並在數組中繪製點時創建一個新的緩衝區畫布。

+0

謝謝Dimple第一個選項引起了我的頭腦,但如果你可以詳細闡述它,因爲我也有添加了UITouchesMoved方法。 – 2012-04-09 13:52:17

相關問題