Swift 中的 CoreAnimation 和 CAReplicatorLayer? [复制]
Posted
技术标签:
【中文标题】Swift 中的 CoreAnimation 和 CAReplicatorLayer? [复制]【英文标题】:CoreAnimation and CAReplicatorLayer in Swift? [duplicate] 【发布时间】:2016-04-17 17:41:47 【问题描述】:我正在将此库从 objc 移植到 Swift,但我无法找出复制器层 instanceCount 对动画没有做任何事情的原因。有什么想法吗?
如果您查看库,它有多个图层实例同时动画,但在我的代码中,一次只有一个图层动画。
https://github.com/shu223/PulsingHalo/blob/master/PulsingHalo/PulsingHaloLayer.m
public class PulsingHaloLayer2: CAReplicatorLayer
var fromValueForRadius: Float = 0.0
var fromValueForAlpha: Float = 0.45
var keyTimeForHalfOpacity: Float = 0.2
var animationDuration: NSTimeInterval = 3.0
var pulseInterval: NSTimeInterval = 0.0
var useTimingFunction: Bool = true
let animationGroup: CAAnimationGroup = CAAnimationGroup()
var repetitions: Float = Float.infinity
var radius: CGFloat = 200.0
didSet
let tempPos = position
let diameter = radius * 2
bounds = CGRect(x: 0.0, y: 0.0, width: diameter, height: diameter)
cornerRadius = radius
position = tempPos
var haloLayerNumber: Int = 4
didSet
instanceCount = 4
instanceDelay = (animationDuration + pulseInterval) / Double(haloLayerNumber)
override init()
super.init()
contentsScale = UIScreen.mainScreen().scale
opacity = 0.0
backgroundColor = UIColor.blueColor().CGColor
haloLayerNumber = 4
setupAnimationGroup()
addAnimation(animationGroup, forKey: "pulse")
required public init(coder aDecoder: NSCoder)
fatalError("init(coder:) has not been implemented")
func setupAnimationGroup()
animationGroup.duration = animationDuration + pulseInterval
animationGroup.repeatCount = repetitions
animationGroup.removedOnCompletion = false
if useTimingFunction
let defaultCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
animationGroup.timingFunction = defaultCurve
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.duration = animationDuration
opacityAnimation.values = [fromValueForAlpha, 0.45, 0]
opacityAnimation.keyTimes = [0, keyTimeForHalfOpacity, 1]
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy")
scaleAnimation.fromValue = fromValueForRadius
scaleAnimation.toValue = 1
scaleAnimation.duration = animationDuration
animationGroup.animations = [opacityAnimation, scaleAnimation]
【问题讨论】:
【参考方案1】:当您调用haloLayerNumber = 4
时,这不会触发didSet
块,因为它发生在init
内部。
您可以使用闭包解决此问题:( haloLayerNumber = 4 )()
。或者您可以从init
内部手动更新instanceCount
/instanceDelay
。
【讨论】:
以上是关于Swift 中的 CoreAnimation 和 CAReplicatorLayer? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
在 Swift 中使用 CoreAnimation 为 UILabel 元素设置动画
使用 Swift 3 为 iOS 中的 UIButton 设置“背景颜色”动画