0

我有一个简单的绘图课。有一个包含颜色选择栏的视图控制器。然后是具有 CGRect 绘制功能的 UIView。

我可以画好,但是当我改变颜色时,所有现有的笔画都会改变。我搞砸了什么?我只想更改新笔画的颜色。

欢迎任何帮助。以下是一些相关的代码片段:

- (void)drawRect:(CGRect)rect
{
    [currentColor setStroke]; 

        for (UIBezierPath *_path in pathArray) 
    [_path strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];  
}

#pragma mark - Touch Methods
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    swiped = NO;

    myPath=[[UIBezierPath alloc]init];
    myPath.lineWidth=10;
    UITouch *touch= [touches anyObject];
    [myPath moveToPoint:[touch locationInView:self]];
    [pathArray addObject:myPath];

    if ([touch tapCount] == 2) {
        [self eraseButtonClicked];
        return;
    }

    lastPoint = [touch locationInView:self];
    lastPoint.y -= 20;


}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    swiped = YES;

    UITouch *touch = [touches anyObject];   
    CGPoint currentPoint = [touch locationInView:self];
    currentPoint.y -= 20;

    [myPath addLineToPoint:[touch locationInView:self]];
    [self setNeedsDisplay];

    UIGraphicsBeginImageContext(self.frame.size);
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 15.0);
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    UIGraphicsEndImageContext();

    lastPoint = currentPoint;

    moved++;    
    if (moved == 10) {
        moved = 0;
    }

}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];   
    if ([touch tapCount] == 2) {
        [self eraseButtonClicked];
        return;
    }
}
4

1 回答 1

1

您的 drawRect: 正在以相同的颜色绘制所有路径。当您调用 [currentColor setStroke] 时,您正在为您绘制的所有笔划设置颜色。您还需要维护笔划的颜色,并在每次调用 strokeWithBlendMode 之前重置颜色。

就像是:

- (void)drawRect:(CGRect)rect
{
    for( int i=0; i<[pathArray count]; i++) {
        [[colorArray objectAtIndex:i] setStroke];
        [[pathArray objectAtIndex:i] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
    }
}

每次向 pathArray 添加路径时,您必须确保将 UIColor 对象添加到 colorArray。

您可以[colorArray addObject:currentColor];在该行之后添加[pathArray addObject:myPath];

于 2012-04-15T02:21:45.223 回答