Невозможно включить отмену / повтор с гладким рисунком свободной руки
Борьба с проблемой в течение многих дней. Надеюсь, я смогу получить ответ здесь. я использовалэтот ссылка, чтобы сгладить мой рисунок свободной рукой. В этом коде я смог установить ширину и цвет линии, но я нахожу это очень трудным, когда я пытаюсь включить в него отмену / повтор, используяэтот ссылка, которая работает нормально при отмене повтора, но ее удаление со стороны свободной руки не является гладким.
После некоторых исследований и кодирования я должен знать, что это рисунок рисунка, который, я думаю, предотвращает отмену / повтор.
В первой ссылке есть файлCachedLIView.h / м» когда я использовал это и попытался включить отмену / повтор в этом, я обнаружил, что в следующем методе:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event // (2)
{
UITouch *touch = [touches anyObject];
CGPoint p = [touch locationInView:self];
[path addLineToPoint:p];
[self drawBitmap]; // (3)
[self setNeedsDisplay];
[path removeAllPoints]; //(4)
}
этот метод вызывает drawBitMap: метод, который фактически генерирует временное изображение каждый раз, когда пользователь поднимает палец, и одновременно удаляет точки из 'дорожка'.
- (void)drawBitmap // (3)
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, 0.0);
[[UIColor blackColor] setStroke];
if (!incrementalImage) // first draw; paint background white by ...
{
UIBezierPath *rectpath = [UIBezierPath bezierPathWithRect:self.bounds]; // enclosing bitmap by a rectangle defined by another UIBezierPath object
[[UIColor greenColor] setFill];
[rectpath fill]; // filling it with white
}
[incrementalImage drawAtPoint:CGPointZero];
//[path stroke];
for (UIBezierPath *_path in pathArray)
[_path strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
incrementalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
Я сохраняю каждый путь в массиве, чтобы я мог отменить / повторить. (взял эту идею из второй ссылки).
ниже приведен полный код этого файла, который я изменил, чтобы включить отмену / повтор:
#import "CachedLIView.h"
@implementation CachedLIView
{
UIBezierPath *path;
UIImage *incrementalImage; // (1)
}
- (id)initWithFrame:(CGRect)frame // (1)
{
if (self = [super initWithFrame:frame])
{
[self setMultipleTouchEnabled:NO]; // (2)
// [self setBackgroundColor:[UIColor whiteColor]];
// path = [[UIBezierPath alloc] init];
// [path setLineWidth:3];
pathArray=[[NSMutableArray alloc]init];
bufferArray=[[NSMutableArray alloc]init];
[self drawBitmap];
}
return self;
}
- (void)drawRect:(CGRect)rect
{
NSLog(@"in drawrect pathArray[count]: %d", pathArray.count);
[incrementalImage drawInRect:rect]; // (3)
//[[UIColor blackColor] setStroke];
//[path stroke];
for (UIBezierPath *_path in pathArray)
[_path strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
path = [[UIBezierPath alloc] init];
path.lineWidth = 3;
UITouch *touch = [touches anyObject];
CGPoint p = [touch locationInView:self];
[path moveToPoint:p];
[pathArray addObject:path];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint p = [touch locationInView:self];
[path addLineToPoint:p];
[self setNeedsDisplay];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event // (2)
{
UITouch *touch = [touches anyObject];
CGPoint p = [touch locationInView:self];
[path addLineToPoint:p];
[self drawBitmap]; // (3)
[self setNeedsDisplay];
[path removeAllPoints]; //(4)
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self touchesEnded:touches withEvent:event];
}
- (void)drawBitmap // (3)
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, 0.0);
[[UIColor blackColor] setStroke];
if (!incrementalImage) // first draw; paint background white by ...
{
UIBezierPath *rectpath = [UIBezierPath bezierPathWithRect:self.bounds]; // enclosing bitmap by a rectangle defined by another UIBezierPath object
[[UIColor greenColor] setFill];
[rectpath fill]; // filling it with white
}
[incrementalImage drawAtPoint:CGPointZero];
//[path stroke];
for (UIBezierPath *_path in pathArray)
[_path strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
incrementalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
#pragma mark - undo/redo
-(void)undoButtonClicked
{
if([pathArray count]>0){
UIBezierPath *_path=[pathArray lastObject];
[bufferArray addObject:_path];
[pathArray removeLastObject];
[self drawBitmap];
[self setNeedsDisplay];
}
}
-(void)redoButtonClicked
{
if([bufferArray count]>0){
UIBezierPath *_path=[bufferArray lastObject];
[pathArray addObject:_path];
[bufferArray removeLastObject];
[self drawBitmap];
[self setNeedsDisplay];
}
}
@end
.h файл это:
#import
@interface CachedLIView : UIView
{
NSMutableArray *pathArray;
NSMutableArray *bufferArray;
UIBezierPath *myPath;
}
-(void)undoButtonClicked;
-(void)redoButtonClicked;
@end
Пожалуйста, помогите мне. Что я делаю не так. Счетчик pathArray работает правильно. но не в состоянии показать эффект отмены / повтора на экране.