我正在尝试构建一个具有重做和撤消功能的绘图应用程序。我的想法是在“touchMoved”中的图层中绘制线条,然后将图层保存在“touchEnded”中。
我不确定我是否正确地绘制到图层,但一切正常,直到我清除我正在绘制的图像并尝试重绘数组中的图层。
- (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]);
}
这是我尝试重绘图层的方法。应用程序在到达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();
}