我试图用重做和撤消功能来构建绘图应用程序。 我的想法是在“touchMoved”的图层中绘制线条,然后将图层保存在“touchEnded”中。iPhone:崩溃时绘制CGLayers存储在阵列
我不确定我是否正确地绘制图层,但一切正常,直到我清除了我正在绘制的图像并尝试重新绘制数组中的图层。
- (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();
}
嗨@Oscar,你的方法成功了吗? – Ranjit 2012-07-12 10:58:04