ActivityIndicatorAnimationBallPulseSync.swift 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // Created by Tom Baranes on 21/08/16.
  3. // Copyright © 2016 IBAnimatable. All rights reserved.
  4. //
  5. import UIKit
  6. public class ActivityIndicatorAnimationBallPulseSync: ActivityIndicatorAnimating {
  7. // MARK: Properties
  8. fileprivate let duration: CFTimeInterval = 0.6
  9. fileprivate var size: CGSize = .zero
  10. fileprivate var circleSize: CGFloat = 0
  11. // MARK: ActivityIndicatorAnimating
  12. public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
  13. let circleSpacing: CGFloat = 2
  14. self.size = size
  15. circleSize = (size.width - circleSpacing * 2) / 3
  16. let x = (layer.bounds.size.width - size.width) / 2
  17. let y = (layer.bounds.size.height - circleSize) / 2
  18. let beginTime = layer.currentMediaTime
  19. let beginTimes: [CFTimeInterval] = [0.07, 0.14, 0.21]
  20. let animation = defaultAnimation
  21. // Draw circles
  22. for i in 0 ..< 3 {
  23. let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color)
  24. let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
  25. y: y,
  26. width: circleSize,
  27. height: circleSize)
  28. animation.beginTime = beginTime + beginTimes[i]
  29. circle.frame = frame
  30. circle.add(animation, forKey: "animation")
  31. layer.addSublayer(circle)
  32. }
  33. }
  34. }
  35. // MARK: - Setup
  36. private extension ActivityIndicatorAnimationBallPulseSync {
  37. var defaultAnimation: CAKeyframeAnimation {
  38. let deltaY = (size.height / 2 - circleSize / 2) / 2
  39. let timingFunction: TimingFunctionType = .easeInOut
  40. let animation = CAKeyframeAnimation(keyPath: .translationY)
  41. animation.keyTimes = [0, 0.33, 0.66, 1]
  42. animation.timingFunctionsType = [timingFunction, timingFunction, timingFunction]
  43. animation.values = [0, deltaY, -deltaY, 0]
  44. animation.duration = duration
  45. animation.repeatCount = .infinity
  46. animation.isRemovedOnCompletion = false
  47. return animation
  48. }
  49. }