0

我正在尝试向 iOS 应用程序添加撤消/重做功能。我希望能够画几条线,然后撤消每条线。我可以擦除整个东西,但这还不够好......我非常感谢帮助,因为这是我第一次尝试使用 CG ......

我的 .h 声明包括:

CGPoint lastPoint;
NSMutableArray *pathArray;
UIBezierPath *myPath;

在.m中,我有:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"%s", __FUNCTION__);
    UITouch *touch = [touches anyObject];
    myPath=[[UIBezierPath alloc]init];
    lastPoint = [touch locationInView:self.view];
    [myPath moveToPoint:lastPoint];
    lastPoint.y -= 20;
    [pathArray addObject:myPath];
    NSLog(@"pathArray count is %i", [pathArray count]);

}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"%s", __FUNCTION__);
    UITouch *touch = [touches anyObject];   
    CGPoint currentPoint = [touch locationInView:self.view];
    currentPoint.y -= 20;   
    UIGraphicsBeginImageContext(self.view.frame.size);
    [drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];

    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush);
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());

    drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
    savedImage.image = drawImage.image;

    UIGraphicsEndImageContext();

    lastPoint = currentPoint;

}

在 touchesBegin 结束时,pathArray 计数始终为零.. :(

为了实现撤消,我正在使用以下代码:

- (void)undoButtonTapped {
    NSLog(@"%s", __FUNCTION__);
    NSLog(@"pathArray count is %i", [pathArray count]);
    if([pathArray count]>0){
        UIBezierPath *_path=[pathArray lastObject];
        [bufferArray addObject:_path];
        [pathArray removeLastObject];
        [self.view setNeedsDisplay];
    }

}

这里的计数也为零..

所有这些都在 UIViewController 中处理。我欢迎任何建议/改进/建议。

谢谢

4

1 回答 1

1

我会说[pathArray count]零的原因是touchesBegan我在您的代码中看不到任何地方

pathArray = [[NSMutableArray alloc] init];

因此,您将消息发送到空指针(允许但不执行任何操作)。

那么你是在分配 pathArray 吗?还是为空??

于 2012-04-12T15:37:51.687 回答