如何在修改路径时重绘CAShapeLayer?

时间:2012-08-11 20:13:34

标签: ios redraw cashapelayer

我正在尝试在我的CAShapeLayer路径中添加子路径,但除非我首先将nil分配给路径,然后重新分配myPath,否则更改不会显示到CAShapeLayer。我尝试使用setNeedsRedisplay,但它不起作用。

这是LoadViewmyPathshapeLayer属性的代码:

// 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];

例如,这是我对路径执行更改的位置。我只需向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;
}

任何人都知道如何处理这个问题?我正在使用iOS 5.0。

2 个答案:

答案 0 :(得分:0)

您应该重置路径超时,在修改路径之前通过removeAllPoints刷新路径图。

在目标C中:

[path removeAllPoints];
[path moveToPoint:p];
[path addLineToPoint:CGPointMake(x, y)];

shapeLayer.path = path.CGPath;

在Swift 4中:

path.removeAllPoints()
path.move(to: p1)
path.addLine(to: p2)

shapeLayer.path = path.cgPath

答案 1 :(得分:-1)

您必须调用[shapeLayer didChangeValueForKey:@"path"]才能让图层重新渲染。