简体   繁体   中英

CAShapeLayer path color changes

So, I know the title of my question may not be the most descriptive so I'll run through it here:

Basically what I have is view with an image (using a layer's contents property) and under that layer I have a Drawing layer which is a CAShapeLayer. In my view where both layers live I also have a CALayerDelegate which, for now, just draws a point using CGPaths with a given color in response to a tap gesture (tap gesture selector calls setNeedsDisplay on the CAShapeLayer). The problem I have is that if I change a color, then tap the view all previous points automatically become the newly selected color...not good...I need each subpath (ie point) to maintain its original color...Maybe some code will shed a little more light on the topic:

The delegate (Note: drawingView.drawingPath is reused):

- (void)drawLayer:(CAShapeLayer *)theLayer
    inContext:(CGContextRef)theContext {


if (CGPointEqualToPoint(drawingView.startPoint, drawingView.endPoint)) {


    CGPathMoveToPoint(drawingView.drawingPath, NULL, drawingView.startPoint.x, drawingView.startPoint.y);
    CGPathAddEllipseInRect(drawingView.drawingPath, NULL, CGRectMake(drawingView.startPoint.x, drawingView.startPoint.y, drawingView.drawRadius, drawingView.drawRadius));

    CGContextSetFillColorWithColor(theContext, drawingView.currentColor.CGColor);
    CGContextBeginPath(theContext);
    CGContextAddPath(theContext, drawingView.drawingPath);
    CGContextFillPath(theContext);

}

}

And my tap gesture recognizer:

- (void)viewTapped:(UITapGestureRecognizer *)recognizer {

CGPoint touchPoint = [recognizer locationInView:recognizer.view];
startPoint = endPoint = touchPoint;
[drawingLayer setNeedsDisplay];

}

I would be ecstatic if someone can show me what I'm doing wrong here! :(

Each time you redraw your layer it will be using information you have previously saved (in this case in your drawing view) to draw everything. You have to be able to represent everything on the screen using only this information. In this case, you are having trouble because you don't save enough information. What you want is not just a drawing path and a color, but a series of drawing paths and colors. You will need to keep a list of objects containing both of those things in your drawingView, and iterate through them, drawing each one. Every time you change the current color, you need to keep track of what has already been drawn and save it along with the old color, so that you don't lose track of which color belongs to which part of the path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM