简体   繁体   中英

How to redraw a CAShapeLayer when modifying his path?

I'm trying to add a subpath to my CAShapeLayer 's path, but the changes doesn't show unless I first assing nil to the path and then I reassign myPath to the CAShapeLayer . I've tried with setNeedsRedisplay but it doesn't works.

This is the code in the 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 is, for example, where I perform the changes to the path. I simply 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;
}

Anyone knows how to deal with this?. I'm using iOS 5.0.

You should reset path overtime you refresh the path drawing via removeAllPoints before you modify 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

您必须调用[shapeLayer didChangeValueForKey:@"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