2012-04-15 52 views
0

我有一個簡單的繪圖類。有一個包含顏色選擇欄的視圖控制器。然後是一個具有CGRect繪製函數的UIView。xCode繪製 - 嘗試在CGRect中保持顏色選擇

我可以畫好,但是當我改變顏色時,所有現有的筆畫都會改變。我搞砸了什麼?我只想改變新筆畫的顏色。

任何幫助將受到歡迎。這裏有一些相關的代碼片段:

- (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

您的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。

你可以行[pathArray addObject:myPath];

+0

泰勒喜後回答添加[colorArray addObject:currentColor];,謝謝。也許我不完全理解..我有七種顏色的分段控制。你是在說我應該製作一系列這些?當用戶點擊一個特定的按鈕時會發生什麼?請您詳細說明一下。感謝您的回答.. David – 2012-04-15 03:01:40

+0

我假設您在用戶點擊顏色控制時更改currentColor變量。這將起作用,但您需要跟蹤用戶在將新路徑添加到pathArray時選擇了什麼顏色。這就是爲什麼我建議將currentColor添加到將與pathArray匹配的新數組中。 – 2012-04-15 04:07:39

+0

另外,如果從pathArray中刪除路徑,則還需要從colorArray中刪除相應的顏色,否則它們將不會同步。 – 2012-04-15 04:20:43