Swift 启动页动画(CAKeyframeAnimation)

前言

项目开发中有个需求,需要给启动页加一个正在加载的动画,先上一个效果图。
这里写图片描述

上图最底层浅色圆圈,我们定义为浅A,转动的为深B,可以看到,深B是围绕着浅A圆圈的边缘旋转的。 下面对实现思想进行分析。

剖析

核心的难点是如何让深B紧凑沿着浅A的圆边做轨迹运动,为此,我们需要确定一个圆轨迹C,然后让深B轨迹C上做圆周运动

这里写图片描述

红色圆圈是轨迹C,它的圆点就是浅A的圆点,然后就是确定半径,为了让深B沿着浅A的边缘运动,所以轨迹C的半径应该是(浅A直径 - 深B直径 )/ 2。
这里写图片描述

代码

确定轨迹C的圆点和半径


let centerX = launchBottomView.center.x
let centerY = launchBottomView.center.y
let radius = (launchBottomView.bounds.size.width - launchTopView.bounds.size.width) / 2

创建椭圆轨迹C


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方法中,否则会导致获取的控件大小不准确。

源码

https://github.com/LSnumber1/CircleAnimation

猜你喜欢

转载自blog.csdn.net/qin_shi/article/details/80204455