iOS CAReplicatorLayer 实现脉冲动画效果
iOS CAReplicatorLayer 实现脉冲动画效果
效果图
脉冲数量、速度、半径、透明度、渐变颜色、方向等都可以设置。可以用于地图标注(Annotation)、按钮长按动画效果(例如录音按钮)等。
代码已上传 GitHub:https://github.com/Silence-GitHub/CoreAnimationDemo
实现原理
实现方法参考:https://github.com/shu223/Pulsator
但是觉得那些代码不够简洁,所以自己写了一个,还加了些功能。
自定义 PulsatorLayer,继承自 CAReplicatorLayer。CAReplicatorLayer 可以复制子图层(Sublayer),被复制出来的子图层可以改变位置、颜色等属性。每一个脉冲(一个渐变的圆形)就是一个被复制出来的子图层。
显示脉冲的图层就是子图层,把它作为 pulseLayer 属性
private var pulseLayer: CALayer!
脉冲子图层一开始不显示,因此初始化时为全透明;通过设置圆角,使 pulseLayer 为圆形
pulseLayer = CALayer()
pulseLayer.opacity = 0
pulseLayer.backgroundColor = outColor
pulseLayer.contentsScale = UIScreen.main.scale
pulseLayer.bounds.size = CGSize(width: maxRadius * 2, height: maxRadius * 2)
pulseLayer.cornerRadius = maxRadius
addSublayer(pulseLayer)
设置 CAReplicatorLayer 的一些属性
// The number of copies to create, including the source layers
instanceCount
// Specifies the delay, in seconds, between replicated copies
instanceDelay
设置复制子图层的数量、创建两个子图层之间的时间间隔。
CAReplicatorLayer 遵循 CAMediaTiming 协议,设置协议属性
// Determines the number of times the animation will repeat
repeatCount = MAXFLOAT
把动画重复次数设置为很大的数,让动画一直重复。
动画效果由 3 个 CABasicAnimation 组成,分别改变脉冲的大小、透明度、背景色颜色
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy")
scaleAnimation.duration = animationDuration
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.duration = animationDuration
let colorAnimation = CABasicAnimation(keyPath: "backgroundColor")
colorAnimation.duration = animationDuration
switch pulseOrientation {
case .out:
scaleAnimation.fromValue = minRadius / maxRadius
scaleAnimation.toValue = 1
opacityAnimation.fromValue = maxAlpha
opacityAnimation.toValue = minAlpha
colorAnimation.fromValue = inColor
colorAnimation.toValue = outColor
case .in:
scaleAnimation.fromValue = 1
scaleAnimation.toValue = minRadius / maxRadius
opacityAnimation.fromValue = minAlpha
opacityAnimation.toValue = maxAlpha
colorAnimation.fromValue = outColor
colorAnimation.toValue = inColor
}
let animationGroup = CAAnimationGroup()
animationGroup.duration = animationDuration + animationInterval
animationGroup.animations = [scaleAnimation, opacityAnimation, colorAnimation]
animationGroup.repeatCount = repeatCount
pulseLayer.add(animationGroup, forKey: kPulseAnimationKey)
以上代码判断了脉冲的方向(由内向外、由外向内),两种方向的动画属性起止取值相反。把这 3 个 CABasicAnimation 加入 CAAnimationGroup 中一起执行。
以上就是实现原理与最核心的代码,具体见 GitHub:https://github.com/Silence-GitHub/CoreAnimationDemo
转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6951948.html