Guest User

Untitled

a guest
Jan 17th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.78 KB | None | 0 0
  1. class Animator(
  2. private val animations: List<Animation>
  3. ) {
  4. constructor(view: View,
  5. startPoint: Point2D = Point2D(view.x, view.y),
  6. endPoint: Point2D) : this(listOf(Animation(view, startPoint, endPoint)))
  7.  
  8. private val transitionState: TransitionState = TransitionState(0)
  9. private val animationQueue: Handler = Handler()
  10.  
  11. /**
  12. * Apply a progression in the animation from [startPoint] to [endPoint] or conversely depending
  13. * on the transition state.
  14. * When the [TransitionState.progress] reach 0 the position of the [view] to animate is at [startPoint]. When it
  15. * reach 100 the view will be at the [endPoint]
  16. *
  17. * @param percent an Integer that must be between 0 and 100 because it's percentage. If the
  18. * given percent is below 0 it
  19. * will override it to 0. Same process when it's over 100.
  20. */
  21. fun progressTo(percent: Int) {
  22. for (anim in animations) {
  23. val finalPercent = if (percent > 100) 100 else if (percent < 0) 0 else percent
  24. if (Math.abs(transitionState.progress - finalPercent) < 10) {
  25. animationQueue.post {
  26. anim.view.x = (Vector2D(anim.startPoint, anim.endPoint) % finalPercent).endPoint.x
  27. anim.view.y = (Vector2D(anim.startPoint, anim.endPoint) % finalPercent).endPoint.y
  28. }
  29. } else {
  30. anim.view.animate().x((Vector2D(anim.startPoint, anim.endPoint) % finalPercent).endPoint.x)
  31. anim.view.animate().y((Vector2D(anim.startPoint, anim.endPoint) % finalPercent).endPoint.y)
  32. }
  33. transitionState.progress = finalPercent
  34. }
  35. }
  36.  
  37. /**
  38. * Finish the animation to the endPoint or startPoint depending on the [TransitionState.progress]
  39. */
  40. fun finishAnimation() {
  41. if (transitionState.progress < 50) {
  42. progressTo(0)
  43. } else if (transitionState.progress >= 50) {
  44. progressTo(100)
  45. }
  46. }
  47. }
  48.  
  49. data class TransitionState(
  50. var progress: Int,
  51. var isOnTransaction: Boolean = progress != 0 && progress != 100
  52. )
  53.  
  54. data class Vector2D(
  55. val startPoint: Point2D,
  56. val endPoint: Point2D
  57. ) {
  58. operator fun rem(percent: Int): Vector2D {
  59. val finalPercent = if (percent > 100) 100 else if (percent < 0) 0 else percent
  60. return Vector2D(startPoint, Point2D(
  61. startPoint.x + ((endPoint.x - startPoint.x) * finalPercent / 100),
  62. startPoint.y + ((endPoint.y - startPoint.y) * finalPercent / 100)
  63. ))
  64. }
  65. }
  66.  
  67. data class Animation(
  68. val view: View,
  69. val startPoint: Point2D = Point2D(view.x, view.y),
  70. val endPoint: Point2D
  71. )
  72.  
  73. data class Point2D(
  74. val x: Float,
  75. val y: Float
  76. )
Add Comment
Please, Sign In to add comment