Animate UIBezierPaths- not working- Swift

流过昼夜 提交于 2021-02-07 04:33:05

问题


I am trying to create an arrow that animates together. But, there are two problems:

1.The lines are not animating, the whole arrow is just appearing on screen

2.The arrow is filled in black, not just the outlines (which I am aiming for)

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)

If anyone could help me with their of those that would be amazing. Any help would be immensely appreciated!! Thanks so much in advance.

Cheers, Theo


回答1:


The problem is this sequence:

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

You cannot add an animation to a layer and then add the layer to the interface. You can only add animation to a layer that is already in the interface.

Also, you need to set the shape layer's fillColor and strokeColor.

Here's actual code. In one place, you would say something like this:

    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

Then, at some later time, you would say:

    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



来源:https://stackoverflow.com/questions/43006518/animate-uibezierpaths-not-working-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!