我試圖用重做和撤消功能來構建繪圖應用程序。 我的想法是在「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