我有一個繪圖應用程序,我想創建一個撤消方法。繪圖發生在TouchesMoved:方法內部。保存CGContextRef
我想創建一個CGContextRef並將其推送到堆棧或將其保存在可以稍後恢復的上下文屬性中,但沒有任何運氣。任何建議都會很棒。以下是我有...
UIImageView *drawingSurface;
CGContextRef undoContext;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UIGraphicsBeginImageContext(self.view.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[drawingSurface.image drawInRect:CGRectMake(0, 0, drawingSurface.image.size.width, drawingSurface.image.size.height)];
UIGraphicsPushContext(context);
// also tried but cant figure how to restore it
undoContext = context;
UIGraphicsEndImageContext();
}
然後我就用我的復原按鈕,觸發一個方法...
- (IBAction)restoreUndoImage {
UIGraphicsBeginImageContext(self.view.frame.size);
UIGraphicsPopContext();
drawingSurface.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
當我運行這一點,我相信我的drawingSurface被分配爲零,因爲它只是刪除圖像中的所有內容。
我的猜測是我不能用pop和push這種方式。但我似乎無法弄清楚如何保存上下文,然後將其推回到drawingSurface上。 Hmmmm。任何幫助將會......很好......有幫助。在此先感謝 -
而且,僅供參考,這是我正在做的畫在屏幕上,這是偉大的工作。這是我的TouchesMoved內:
UIGraphicsBeginImageContext(self.view.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[drawingSurface.image drawInRect:CGRectMake(0, 0, drawingSurface.image.size.width, drawingSurface.image.size.height)];
CGContextSetLineCap(context, kCGLineCapRound); //kCGLineCapSquare, kCGLineCapButt, kCGLineCapRound
CGContextSetLineWidth(context, self.brush.size); // for size
CGContextSetStrokeColorWithColor (context,[currentColor CGColor]);
CGContextBeginPath(context);
CGContextMoveToPoint(context, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(context, currentPoint.x, currentPoint.y);
CGContextStrokePath(context);
drawingSurface.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
神奇的,深思熟慮的答案。不知道爲什麼OP不接受這一點。 – Tim 2012-05-31 21:35:44