Tôi có ứng dụng vẽ mà tôi muốn tạo phương thức hoàn tác. Bản vẽ diễn ra bên trong phương thức TouchesMoved:Tiết kiệm CGContextRef
Tôi đang cố gắng tạo một CGContextRef và đẩy nó vào ngăn xếp HOẶC lưu nó vào một thuộc tính ngữ cảnh có thể được khôi phục sau nhưng không có bất kỳ may mắn nào. Bất cứ lời khuyên nào cũng tuyệt vời cả. Dưới đây là những gì tôi có ...
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();
}
Sau đó, tôi có một phương pháp kích hoạt bởi nút undo tôi ...
- (IBAction)restoreUndoImage {
UIGraphicsBeginImageContext(self.view.frame.size);
UIGraphicsPopContext();
drawingSurface.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
Khi tôi chạy này, tôi tin rằng drawingSurface của tôi đang được giao bằng không bởi vì nó chỉ xóa mọi thứ trong hình ảnh.
Tôi đoán là tôi không thể sử dụng pop và đẩy theo cách này. Nhưng tôi không thể tìm ra cách để lưu bối cảnh và sau đó đẩy nó trở lại bản vẽSurface. Hmmmm. Bất kỳ sự giúp đỡ nào cũng sẽ ... tốt ... hữu ích. Cảm ơn trước -
Và, chỉ để tham khảo, dưới đây là những gì tôi đang làm để vẽ lên màn hình đang hoạt động tuyệt vời. Đây là bên trong TouchesMoved của tôi:
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();
Câu trả lời tuyệt vời, được suy nghĩ cẩn thận. Không chắc tại sao OP không chấp nhận điều này. – Tim