Search code examples
swiftanimationswift4geometryuibezierpath

UIBezierPath circle animation distortion


So, I'm pretty new to animation and BezierPaths. Here's my code. Can you please help me figure out what's causing the distortion?

    let circleLayer = CAShapeLayer()
    let radius: CGFloat = 100.0
    let beginPath = UIBezierPath(arcCenter: view.center, radius: 0, startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
    let endPath = UIBezierPath(arcCenter: view.center, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)

    circleLayer.fillColor = UIColor.red.cgColor
    circleLayer.path = beginPath.cgPath

    circleLayer.removeAllAnimations()

    let scaleAnimation = CABasicAnimation(keyPath: "path")
    scaleAnimation.fromValue = beginPath.cgPath
    scaleAnimation.toValue = endPath.cgPath

    let alphaAnimation = CABasicAnimation(keyPath: "opacity")
    alphaAnimation.fromValue = 1
    alphaAnimation.toValue = 0

    let animations = CAAnimationGroup()
    animations.duration = 2
    animations.repeatCount = .greatestFiniteMagnitude
    animations.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
    animations.animations = [scaleAnimation, alphaAnimation]

    circleLayer.add(animations, forKey: "animations")

    self.view.layer.addSublayer(circleLayer)

enter image description here

enter image description here

enter image description here


Solution

  • Your goal is to make the circle grow from a center point?

    The problem you face with arc animations is that the beginning path and ending path must have the same number of points in them. My guess is that with a radius of 0, the system simplifies your starting path to a single point, or even an empty path.

    You might want to instead use a starting radius of 0.01.

    Another option would be to animate the layer's scale from 0 to 1 and set the size of the image to the desired end size.