前言
實現一種菜單,菜單從頂部彈入,然後從底部消失,頂部彈入時,有一個上下抖動的過程,底部消失時,先向上滑動,然後再向下滑動消失。
效果圖如下:
引入依賴
implementation 'com.android.support:support-dynamic-animation:27.1.1'1
創建SpringAnimation需要三個參數。
•做動畫的View
•做動畫的類型(DynamicAnimation)
ALPHAROTATIONROTATION_XROTATION_YSCALE_XSCALE_YSCROLL_XSCROLL_YTRANSLATION_XTRANSLATION_YTRANSLATION_ZXYZ
上邊的gif圖為DynamicAnimation為TRANSLATION_Y的預覽圖,現在我們把參數設置為ROTATION,
SpringAnimation signUpBtnAnimY = new SpringAnimation(constraintLayout, DynamicAnimation.ROTATION, 0);
效果圖如下:
- 創建動畫的最終位置
相對View的當前位置的偏移量。
SpringForce
為了讓動畫流暢,有彈簧的性質,需要設置SpringForce的相關參數。
- Stiffness
即剛度,此值越大,產生的里越大,動畫中彈性效果越不明顯,運動比較快。
STIFFNESS_HIGHSTIFFNESS_LOWSTIFFNESS_MEDIUMSTIFFNESS_VERY_LOW
設置方法為:
signUpBtnAnimY.getSpring().setStiffness(SpringForce.STIFFNESS_LOW);
•DampingRatio阻尼比
即阻尼比,此值越大,彈簧效果停止的越快
DAMPING_RATIO_HIGH_BOUNCYDAMPING_RATIO_LOW_BOUNCYDAMPING_RATIO_MEDIUM_BOUNCYDAMPING_RATIO_NO_BOUNCY
設置方法為:
signUpBtnAnimY.getSpring().setDampingRatio(SpringForce.DAMPING_RATIO_MEDIUM_BOUNCY);
StartVelocity
啟動速度,默認速度為0,單位是px/second.
整體代碼如下:
•顯示菜單動畫
public void showAnimal() { setVisibility(View.VISIBLE); SpringAnimation signUpBtnAnimY = new SpringAnimation(constraintLayout, DynamicAnimation.TRANSLATION_Y, 0); signUpBtnAnimY.getSpring().setStiffness(SpringForce.STIFFNESS_LOW); signUpBtnAnimY.getSpring().setDampingRatio(SpringForce.DAMPING_RATIO_MEDIUM_BOUNCY); signUpBtnAnimY.setStartVelocity(5000); signUpBtnAnimY.start(); }•隱藏菜單動畫
public void hideAnimal() { height = (ScreenTools.getScreenHeight(getContext()) - constraintLayout.getHeight()) / 2 + constraintLayout.getHeight() + ScreenTools.dp2px(getContext(),50); ObjectAnimator animator = ObjectAnimator.ofFloat(constraintLayout, "translationY", 0f, -100f, height); animator.setDuration(600); animator.setInterpolator(new DecelerateInterpolator()); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); setVisibility(GONE); reLayout(); } }); animator.start(); }源碼:https://github.com/LSnumber1/StudySpringAnimation
總結
以上所述是小編給大家介紹的SpringAnimation 實現菜單從頂部彈出從底部消失動畫效果,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!