xCode draw - 尝试在CGRect中维护颜色选择

时间:2012-04-15 00:35:44

标签: xcode core-graphics cgrect

我有一个简单的绘图类。有一个视图控制器,包括一个颜色选择栏。然后是一个具有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;
    }
}

1 个答案:

答案 0 :(得分: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的路径时,都必须确保向colorArray添加UIColor对象。

您可以在[colorArray addObject:currentColor];

之后添加[pathArray addObject:myPath];