ActivityIndicatorAnimationBallBeat.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //
  2. // Created by Tom Baranes on 21/08/16.
  3. // Copyright © 2016 IBAnimatable. All rights reserved.
  4. //
  5. import UIKit
  6. public class ActivityIndicatorAnimationBallBeat: ActivityIndicatorAnimating {
  7. // MARK: Properties
  8. fileprivate let duration: CFTimeInterval = 0.7
  9. // MARK: ActivityIndicatorAnimating
  10. public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
  11. let circleSpacing: CGFloat = 2
  12. let circleSize = (size.width - circleSpacing * 2) / 3
  13. let x = (layer.bounds.size.width - size.width) / 2
  14. let y = (layer.bounds.size.height - circleSize) / 2
  15. let beginTime = layer.currentMediaTime
  16. let beginTimes = [0.35, 0, 0.35]
  17. // Draw circles
  18. for i in 0 ..< 3 {
  19. let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color)
  20. let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
  21. y: y,
  22. width: circleSize,
  23. height: circleSize)
  24. animation.beginTime = beginTime + beginTimes[i]
  25. circle.frame = frame
  26. circle.add(animation, forKey: "animation")
  27. layer.addSublayer(circle)
  28. }
  29. }
  30. }
  31. // MARK: - Setup
  32. private extension ActivityIndicatorAnimationBallBeat {
  33. var scaleAnimation: CAKeyframeAnimation {
  34. let scaleAnimation = CAKeyframeAnimation(keyPath: .scale)
  35. scaleAnimation.keyTimes = [0, 0.5, 1]
  36. scaleAnimation.values = [1, 0.75, 1]
  37. scaleAnimation.duration = duration
  38. return scaleAnimation
  39. }
  40. var opacityAnimation: CAKeyframeAnimation {
  41. let opacityAnimation = CAKeyframeAnimation(keyPath: .opacity)
  42. opacityAnimation.keyTimes = [0, 0.5, 1]
  43. opacityAnimation.values = [1, 0.2, 1]
  44. opacityAnimation.duration = duration
  45. return opacityAnimation
  46. }
  47. var animation: CAAnimationGroup {
  48. let animation = CAAnimationGroup()
  49. animation.animations = [scaleAnimation, opacityAnimation]
  50. animation.timingFunctionType = .linear
  51. animation.duration = duration
  52. animation.repeatCount = .infinity
  53. animation.isRemovedOnCompletion = false
  54. return animation
  55. }
  56. }