I'm trying to build a drawing app with redo and undo functionality. My idea is to draw lines in a layer in "touchMoved", then saving the layer in "touchEnded".
I'm not shure that I am drawing to the layer correct, everything works fine though, until I clear the image I'm drawing in on and try to redraw the layers in the array.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
UIGraphicsBeginImageContext(self.imageView.frame.size);
[self.imageView.image drawInRect:self.imageView.frame];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextRef myContext;
layerRef = CGLayerCreateWithContext(context, self.imageView.frame.size, NULL);
if (self.layer == nil) {
myContext =CGLayerGetContext(layerRef);
CGContextSetLineCap(myContext, kCGLineCapRound);
CGContextSetLineWidth(myContext, 5.0);
CGContextSetLineJoin(myContext, kCGLineJoinRound);
CGContextSetRGBStrokeColor(myContext, 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(myContext);
CGContextMoveToPoint(myContext, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(myContext, currentPoint.x, currentPoint.y);
CGContextStrokePath(myContext);
CGContextDrawLayerAtPoint(context, CGPointMake(00, 00),layerRef);
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lastPoint = currentPoint;
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (self.layerArray != nil) {
NSLog(@"Saving layer");
[self.layerArray addObject:[[NSValue alloc] initWithBytes:layerRef objCType:@encode(CGLayerRef)]];
CGLayerRelease(layerRef);
}
NSLog(@"%d",[layerArray count]);
}
Here is the method I'm trying to redraw the layer in.
The app crashes when it reaches the the CGContextDrawLayerAtPoint()
- (IBAction)redrawViewButton:(id)sender {
UIGraphicsBeginImageContext(self.imageView.frame.size);
[self.imageView.image drawInRect:self.imageView.frame];
NSValue *val = [layerArray objectAtIndex:0];
CGLayerRef layerToShow;
[val getValue:&layerToShow];
CGContextRef context = CGLayerGetContext(layerToShow);
CGContextDrawLayerAtPoint(context, CGPointMake(00, 00),layerToShow);
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}