I'm trying to add an undo/redo function to an iOS app. I want to be able to draw several lines, then undo each one.. I can erase the whole thing, but that's not good enough... I would really appreciate help as this is my first foray into using CG..
My .h declarations include:
CGPoint lastPoint;
NSMutableArray *pathArray;
UIBezierPath *myPath;
In .m, I have:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"%s", __FUNCTION__);
UITouch *touch = [touches anyObject];
myPath=[[UIBezierPath alloc]init];
lastPoint = [touch locationInView:self.view];
[myPath moveToPoint:lastPoint];
lastPoint.y -= 20;
[pathArray addObject:myPath];
NSLog(@"pathArray count is %i", [pathArray count]);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"%s", __FUNCTION__);
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
currentPoint.y -= 20;
UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
savedImage.image = drawImage.image;
UIGraphicsEndImageContext();
lastPoint = currentPoint;
}
At the end of touchesBegin, the pathArray count is always zero.. :(
To implement the undo, I'm using this code:
- (void)undoButtonTapped {
NSLog(@"%s", __FUNCTION__);
NSLog(@"pathArray count is %i", [pathArray count]);
if([pathArray count]>0){
UIBezierPath *_path=[pathArray lastObject];
[bufferArray addObject:_path];
[pathArray removeLastObject];
[self.view setNeedsDisplay];
}
}
count here is also zero..
All of this is being handled in a UIViewController. I would welcome any advice/improvements/suggestions.
Thanks