2017-03-24 23 views
1

我正在尝试创建一个可以一起呈现动画的箭头。但是,有两个问题:Animate UIBezierPaths- not working- Swift

1.线没有动画,整个箭头只是出现在屏幕上

2.箭头以黑色填充,不只是大纲(其中我的目标为)

let shapeLayer = CAShapeLayer() 
let bezierPath = UIBezierPath() 

//set up lines 
bezierPath.move(to: CGPoint(x: 50.5, y: 158.5)) 
bezierPath.addLine(to: CGPoint(x: 221.5, y: 158.5)) 
bezierPath.addLine(to: CGPoint(x: 171.5, y: 108.5)) 
bezierPath.addLine(to: CGPoint(x: 197.5, y: 82.5)) 
bezierPath.addLine(to: CGPoint(x: 292.5, y: 177.5)) 
bezierPath.addLine(to: CGPoint(x: 197.5, y: 272.5)) 
bezierPath.addLine(to: CGPoint(x: 171.5, y: 246.5)) 
bezierPath.addLine(to: CGPoint(x: 221.5, y: 196.5)) 
bezierPath.addLine(to: CGPoint(x: 50.5, y: 196.5)) 
bezierPath.addLine(to: CGPoint(x: 50.5, y: 158.5)) 
UIColor.black.setStroke() 
bezierPath.lineWidth = 1 
bezierPath.stroke() 
shapeLayer.path = bezierPath.cgPath 

// set up animation 
let animation2 = CABasicAnimation(keyPath: "strokeEnd") 

animation2.fromValue = 0.0 
animation2.toValue = 1.0 
animation2.duration = 2.5 
shapeLayer.add(animation2, forKey: "drawLineAnimation") 

eeView.layer.addSublayer(shapeLayer) 

如果任何人都可以帮助我的那些将是惊人的。任何帮助将非常感谢!非常感谢提前。

干杯, 西奥

回答

4

问题是这样的顺序:

shapeLayer.add(animation2, forKey: "drawLineAnimation") 
eeView.layer.addSublayer(shapeLayer) 

您可以将动画无法添加到一个图层,然后将图层添加到接口。您只能将界面中的动画添加到已经是的图层中。

此外,您需要设置形状图层的fillColorstrokeColor

这里是实际的代码。在一个地方,你会说这样的事情:

let shapeLayer = CAShapeLayer() 
    shapeLayer.fillColor = UIColor.clear.cgColor 
    shapeLayer.strokeColor = UIColor.black.cgColor 
    eeView.layer.addSublayer(shapeLayer) 
    self.shape = shapeLayer // self.shape is a property 

然后,在一些时候,你会说:

let shapeLayer = self.shape! 
    let bezierPath = UIBezierPath() 
    // ... rest of your code goes here: create path, add path to shape layer ... 
    // ... create animation, add animation to shape layer 

enter image description here

+0

嗯......那没似乎修复它。仍然只是一次出现在视图上。非常感谢您的回答! –

+1

不,我的答案正常。我将添加代码。 – matt

+1

添加了代码和屏幕录像,显示它的工作原理。 – matt