Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Animator(
- private val animations: List<Animation>
- ) {
- constructor(view: View,
- startPoint: Point2D = Point2D(view.x, view.y),
- endPoint: Point2D) : this(listOf(Animation(view, startPoint, endPoint)))
- private val transitionState: TransitionState = TransitionState(0)
- private val animationQueue: Handler = Handler()
- /**
- * Apply a progression in the animation from [startPoint] to [endPoint] or conversely depending
- * on the transition state.
- * When the [TransitionState.progress] reach 0 the position of the [view] to animate is at [startPoint]. When it
- * reach 100 the view will be at the [endPoint]
- *
- * @param percent an Integer that must be between 0 and 100 because it's percentage. If the
- * given percent is below 0 it
- * will override it to 0. Same process when it's over 100.
- */
- fun progressTo(percent: Int) {
- for (anim in animations) {
- val finalPercent = if (percent > 100) 100 else if (percent < 0) 0 else percent
- if (Math.abs(transitionState.progress - finalPercent) < 10) {
- animationQueue.post {
- anim.view.x = (Vector2D(anim.startPoint, anim.endPoint) % finalPercent).endPoint.x
- anim.view.y = (Vector2D(anim.startPoint, anim.endPoint) % finalPercent).endPoint.y
- }
- } else {
- anim.view.animate().x((Vector2D(anim.startPoint, anim.endPoint) % finalPercent).endPoint.x)
- anim.view.animate().y((Vector2D(anim.startPoint, anim.endPoint) % finalPercent).endPoint.y)
- }
- transitionState.progress = finalPercent
- }
- }
- /**
- * Finish the animation to the endPoint or startPoint depending on the [TransitionState.progress]
- */
- fun finishAnimation() {
- if (transitionState.progress < 50) {
- progressTo(0)
- } else if (transitionState.progress >= 50) {
- progressTo(100)
- }
- }
- }
- data class TransitionState(
- var progress: Int,
- var isOnTransaction: Boolean = progress != 0 && progress != 100
- )
- data class Vector2D(
- val startPoint: Point2D,
- val endPoint: Point2D
- ) {
- operator fun rem(percent: Int): Vector2D {
- val finalPercent = if (percent > 100) 100 else if (percent < 0) 0 else percent
- return Vector2D(startPoint, Point2D(
- startPoint.x + ((endPoint.x - startPoint.x) * finalPercent / 100),
- startPoint.y + ((endPoint.y - startPoint.y) * finalPercent / 100)
- ))
- }
- }
- data class Animation(
- val view: View,
- val startPoint: Point2D = Point2D(view.x, view.y),
- val endPoint: Point2D
- )
- data class Point2D(
- val x: Float,
- val y: Float
- )
Add Comment
Please, Sign In to add comment