当前位置: 动力学知识库 > 问答 > 编程问答 >

core graphics - xCode draw - Trying to maintain color choice in CGRect

问题描述:

I have a simple drawing class. There is a view controller that includes a color selection bar. Then a UIView that has the CGRect draw functions.

I can draw ok, but when I change the color, all existing strokes are changed. What have I messed up? I want to only change colors for new strokes.

Any help would be welcome. Here are some relevant code snippets:

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

}

}

网友答案:

Your drawRect: is drawing all the paths in the same colour. When you call [currentColor setStroke], you are setting the colour for all the strokes you draw. You'll need to maintain the colours for the strokes as well, and reset the colour before each call to strokeWithBlendMode.

Something like:

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

You'll have to make sure you add a UIColor object to the colorArray every time you add a path to pathArray.

You could add [colorArray addObject:currentColor]; after the line [pathArray addObject:myPath];

分享给朋友:
您可能感兴趣的文章:
随机阅读: