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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM