How to do Flip Animation in Android
In the last post, I list a category of Animations in Android platform, that’s my road map to learn android animation and this post will give a specific live example about the flip transformation which is really common in our apps.
In the last post, I list the two kinds of animation strategies in Android, Animation and more powerful Animator. Both of them can implement the flip animation in our case, and my purpose is to compare those two ways.
Animation
We can’t use the predefined Animation subclass directly, there are scale, rotate, alpha and translate Animations, but we can’t use rotate animation to build the card flip effect. We should subclass Animation class to define the flip effect.
package suzp1984.github.io.exapidemo.animation import android.graphics.Camera import android.view.animation.Animation import android.view.animation.Transformation class FlipAnimation(fromDegre: Float, toDegre: Float, centerX : Float, centerY : Float) : Animation() { var fromDegree : Float = 0.0f var toDegree : Float = 0.0f var centerX : Float = 0.0f var centerY : Float = 0.0f lateinit var camera : Camera init { this.fromDegree = fromDegre this.toDegree = toDegre this.centerX = centerX this.centerY = centerY } override fun initialize(width: Int, height: Int, parentWidth: Int, parentHeight: Int) { super.initialize(width, height, parentWidth, parentHeight) camera = Camera() } override fun applyTransformation(interpolatedTime: Float, t: Transformation) { val degrees = fromDegree + (toDegree - fromDegree) * interpolatedTime val camera = camera val matrix = t.matrix camera.save() camera.rotateY(degrees) camera.getMatrix(matrix) camera.restore() matrix.preTranslate(-centerX, -centerY) matrix.postTranslate(centerX, centerY) } }
Then How to use it:
val animation = FlipAnimation(startAngor, endAngor, 0.0f, flipCardView.height / 2.0f) animation.duration = 1000 animation.interpolator = AccelerateInterpolator() animation.fillAfter = true animation.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationRepeat(animation: Animation?) { } override fun onAnimationEnd(animation: Animation?) { // flipCardView.rotationY = endAngor flipCardView.clearAnimation() if (!toggle) { flipCardView.visibility = View.INVISIBLE } } override fun onAnimationStart(animation: Animation?) { } }) flipCardView.startAnimation(animation)
Animator
Animator has the more advanced way to animator anything, I will use Object Animator to do the card-flip.
flipCardView.pivotX = 0.0f flipCardView.pivotY = flipCardView.height / 2.0f val animator = ObjectAnimator.ofFloat(flipCardView, "rotationY", startDeg, endDeg) animator.setDuration(1000); animator.interpolator = AccelerateInterpolator() animator.start()
Be focus the first two line, which set up two properties of View, pivotX, and pivotY. These two properties setup the location of the rotation point during rotation.
Comments
Post a Comment