How to move image in circle swift

2020-06-27 09:15发布

问题:

Can anybody explain to me how I can create the path of circle and move an image around it.

What I need:

let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100,y: 100), radius:  CGFloat(20), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

I discovered how do the path of circle, but the rest I don't know to do. I'm new to iOS development.

And, I need this action begin when I open the page.

回答1:

Check this code, the objectToMove is an UIView from storyBoard to test, here I am using your path code but I had added more radius

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var objectToMove: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        let orbit = CAKeyframeAnimation(keyPath: "position")
        var affineTransform = CGAffineTransformMakeRotation(0.0)
        affineTransform = CGAffineTransformRotate(affineTransform, CGFloat(M_PI))
        let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100 - (100/2),y: 100 - (100/2)), radius:  CGFloat(100), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
        orbit.path = circlePath.CGPath
        orbit.duration = 4
        orbit.additive = true
        orbit.repeatCount = 100
        orbit.calculationMode = kCAAnimationPaced
        orbit.rotationMode = kCAAnimationRotateAuto

        objectToMove.layer .addAnimation(orbit, forKey: "orbit")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

I hope this helps you, Regards