iosswiftanimationuiviewcgaffinetransform

How do I animate a UIView along a circular path?


In Swift code, how can I start and animate a UIView so that it moves in a motion along a circular path, then bring it to an end gracefully? Is it possible to achieve this using a CGAffineTransform animation?

I have prepared a GIF below showing the type of animation I'm trying to achieve.

enter image description here


Solution

  • Updated: Update code to Swift 5.6

    Use UIBezierPath and CAKeyFrameAnimation.

    Here is the code:

    let circlePath = UIBezierPath(arcCenter: view.center, radius: 20, startAngle: 0, endAngle: .pi*2, clockwise: true)
    
    let animation = CAKeyframeAnimation(keyPath: #keyPath(CALayer.position))
    animation.path = circlePath.cgPath
    animation.duration = 1
    animation.repeatCount = .infinity
    
    let squareView = UIView()
    // whatever the value of origin for squareView will not affect the animation
    squareView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
    squareView.backgroundColor = .lightGray
    view.addSubview(squareView)
    // you can also pass any unique string value for key
    squareView.layer.add(animation, forKey: nil)
    
    // circleLayer is only used to show the circle animation path
    let circleLayer = CAShapeLayer()
    circleLayer.path = circlePath.cgPath
    circleLayer.strokeColor = UIColor.black.cgColor
    circleLayer.fillColor = UIColor.clear.cgColor
    view.layer.addSublayer(circleLayer)
    

    Here is the screenshot:

    enter image description here

    Moreover, you can set the anchorPoint property of squareView.layer to make the view not animate anchored in it's center. The default value of anchorPoint is (0.5, 0.5) which means the center point.