How to redraw a CAShapeLayer when changing a path?

I am trying to add a subpath to my CAShapeLayer path, but the changes are not displayed unless I first passed nil to the path and then reassigned myPath to CAShapeLayer . I tried with setNeedsRedisplay , but it does not work.

This is the code in LoadView , where myPath and shapeLayer are properties:

 // The CGMutablePathRef CGPathMoveToPoint(myPath, nil, self.view.center.x, self.view.center.y); CGPathAddLineToPoint(myPath, nil, self.view.center.x + 100.0, self.view.center.y - 100.0); // The CAShapeLayer shapeLayer = [CAShapeLayer layer]; shapeLayer.path = myPath; shapeLayer.strokeColor = [UIColor greenColor].CGColor; shapeLayer.lineWidth = 2.0; [self.view.layer addSublayer:shapeLayer]; 

And this, for example, when I make changes along the way. I just add a new subpath to myPath :

 - (void)handleOneFingerSingleTapGesture:(UIGestureRecognizer *)sender { // I add a new subpath to 'myPath' CGPathMoveToPoint(myPath, nil, self.view.center.x, self.view.center.y); CGPathAddLineToPoint(myPath, nil, self.view.center.x + 100.0, self.view.center.y + 100.0); // I must do this to show the changes shapeLayer.path = nil; shapeLayer.path = myPath; } 

Does anyone know how to deal with this ?. I am using iOS 5.0.

+4
source share
2 answers

You must reset to exceed the path time when you update the path drawing with removeAllPoints before changing the path.

In Objective C:

 [path removeAllPoints]; [path moveToPoint:p]; [path addLineToPoint:CGPointMake(x, y)]; shapeLayer.path = path.CGPath; 

In Swift 4:

 path.removeAllPoints() path.move(to: p1) path.addLine(to: p2) shapeLayer.path = path.cgPath 
0
source

You must call [shapeLayer didChangeValueForKey:@"path"] to get a layer for re-rendering.

-1
source

All Articles