項目開發中有個需求,須要給啓動頁加一個正在加載的動畫,先上一個效果圖。git
上圖最底層淺色圓圈,咱們定義爲淺A,轉動的爲深B,能夠看到,深B是圍繞着淺A圓圈的邊緣旋轉的。 下面對實現思想進行分析。github
核心的難點是如何讓深B緊湊沿着淺A的圓邊作軌跡運動,爲此,咱們須要肯定一個圓軌跡C,而後讓深B在軌跡C上作圓周運動動畫
紅色圓圈是軌跡C,它的圓點就是淺A的圓點,而後就是肯定半徑,爲了讓深B沿着淺A的邊緣運動,因此軌跡C的半徑應該是(淺A直徑 - 深B直徑 )/ 2。spa
肯定軌跡C的圓點和半徑code
let centerX = launchBottomView.center.x let centerY = launchBottomView.center.y let radius = (launchBottomView.bounds.size.width - launchTopView.bounds.size.width) / 2
建立橢圓軌跡Corm
let boundingRect = CGRect(x: centerX - radius, y: centerY - radius, width: radius * 2, height: radius * 2) let path = CGPath(ellipseIn: boundingRect, transform: nil)
深B作動畫圖片
let animation = CAKeyframeAnimation(keyPath:"position") animation.duration = 3 animation.path = path animation.calculationMode = kCAAnimationPaced animation.repeatCount = HUGE launchTopView.layer.add(animation, forKey:"Move")
調用肯定圓點、半徑、動畫的位置要寫在 viewDidAppear方法中,不然會致使獲取的控件大小不許確。