Search code examples
iosiphoneswift4uibezierpathxcode9.3

I want to Rotate 3 different images on different location in 360 degree in swift 4 using UIBezierPath


I want to Rotate 3 different images on different location in 360 degree in swift 4 using UIBezierPath. i am able to move single image like this in image. with this code

import UIKit

class ViewController: UIViewController {

 override func viewDidLoad() {
    super.viewDidLoad()

    let circlePath = UIBezierPath(arcCenter: CGPoint(x: view.frame.midX, y: view.frame.midY), radius: 120, startAngle: 0, endAngle:CGFloat(Double.pi)*2, clockwise: true)

    let animation = CAKeyframeAnimation(keyPath: "position");
    animation.duration = 5
    animation.repeatCount = MAXFLOAT
    animation.path = circlePath.cgPath

    let moon = UIImageView()
    moon.frame = CGRect(x:0, y:0, width:40, height:40);
    moon.image = UIImage(named: "moon.png")
    view.addSubview(moon)
    moon.layer.add(animation, forKey: nil)



 }

}

and I want to rotate 3 different images on different Angle and Position like this.i want to rotate all 3 different images like in this

Anyone here who can update my code according to the image above I want Thank You in Advance Cheers! :) .


Solution

  • I tried with your code and its working. I made a function to rotate a imageView.

    func startMovingAView(startAnlge: CGFloat, endAngle: CGFloat) {
    
            let circlePath = UIBezierPath(arcCenter: CGPoint(x: view.frame.midX, y: view.frame.midY), radius: 120, startAngle: startAnlge, endAngle:endAngle, clockwise: true)
    
            let animation = CAKeyframeAnimation(keyPath: "position");
            animation.duration = 5
            animation.repeatCount = MAXFLOAT
            animation.path = circlePath.cgPath
    
            let moon = UIImageView()
            moon.frame = CGRect(x:0, y:0, width:40, height:40);
            moon.image = UIImage(named: "moon.png")
            view.addSubview(moon)
            moon.layer.add(animation, forKey: nil)
     }
    

    And here is the angles what I pass for each imageView:

    /// For first imageView
    var startAngle: CGFloat = 0.0
    var endAngle: CGFloat = CGFloat(Double.pi) * 2.0
    startMovingAView(startAnlge: startAngle, endAngle: endAngle)
    
    /// For second imageView   
    startAngle = CGFloat(Double.pi/2.0)
    endAngle = CGFloat(Double.pi) * 2.5
    startMovingAView(startAnlge: startAngle, endAngle: endAngle)
    
    /// For third imageView  
    startAngle = CGFloat(Double.pi)
    endAngle = CGFloat(Double.pi) * 3.0
    startMovingAView(startAnlge: startAngle, endAngle: endAngle)
    

    We just need to find the angles with same difference so that in 5 seconds duration the imageView have to travel the same distance so all objects moves with constant and same speed.