Created
July 11, 2018 18:15
-
-
Save mahdi-malv/1837a372271888f33ff22085dfd51aa3 to your computer and use it in GitHub Desktop.
Flip animation for any view (Also supports two views) - Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Creates a 3D flip animation between two views. | |
* | |
* @param fromView First view in the transition. | |
* @param toView Second view in the transition. | |
*/ | |
class FlipAnimation(private var fromView: View?, private var toView: View?) : Animation() { | |
private var camera: Camera? = null | |
private var centerX: Float = 0.toFloat() | |
private var centerY: Float = 0.toFloat() | |
private var forward = true | |
init { | |
duration = 500 | |
fillAfter = false | |
interpolator = AccelerateDecelerateInterpolator() | |
} | |
fun reverse() { | |
forward = false | |
val switchView = toView | |
toView = fromView | |
fromView = switchView | |
} | |
override fun initialize(width: Int, height: Int, parentWidth: Int, parentHeight: Int) { | |
super.initialize(width, height, parentWidth, parentHeight) | |
centerX = (width / 2).toFloat() | |
centerY = (height / 2).toFloat() | |
camera = Camera() | |
} | |
override fun applyTransformation(interpolatedTime: Float, t: Transformation) { | |
// Angle around the y-axis of the rotation at the given time | |
// calculated both in radians and degrees. | |
val radians = Math.PI * interpolatedTime | |
var degrees = (180.0 * radians / Math.PI).toFloat() | |
// Once we reach the midpoint in the animation, we need to hide the | |
// source view and show the destination view. We also need to change | |
// the angle by 180 degrees so that the destination does not come in | |
// flipped around | |
if (interpolatedTime >= 0.5f) { | |
degrees -= 180f | |
fromView!!.visibility = View.GONE | |
toView!!.visibility = View.VISIBLE | |
} | |
if (forward) | |
degrees = -degrees //determines direction of rotation when flip begins | |
val matrix = t.matrix | |
camera!!.save() | |
camera!!.rotateY(degrees) | |
camera!!.getMatrix(matrix) | |
camera!!.restore() | |
matrix.preTranslate(-centerX, -centerY) | |
matrix.postTranslate(centerX, centerY) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun animateFab(v: View, v2: View) { // If it's only one view pass a view for both | |
val flipAnimation = FlipAnimation(v, v2) | |
if (v.visibility == View.GONE) { | |
flipAnimation.reverse() | |
} else { | |
v.startAnimation(flipAnimation) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment