119

用 ConstraintLayout 和 ConstraintSet 实现 Android 关键帧动画

 6 years ago
source link: https://zhuanlan.zhihu.com/p/31984220?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

用 ConstraintLayout 和 ConstraintSet 实现 Android 关键帧动画

编程等 2 个话题下的优秀答主
简评:话说现在 Google 的 Android 视频里都是用 Kotlin 做示例了啊。

首先,什么是关键帧动画(keyframe animations)?

简单的说就是给出两个变化前后的关键状态,然后中间的变化由程序自动实现。这里就根据 Android Developers 的新视频,介绍下怎么通过 ConstraintLayoutConstraintSet 实现类似下面这样的关键帧动画(最少只需要四行代码)。

动图封面

首先,在初始布局文件中将要动画展示的 TextView 先移出屏幕,使得图片覆盖整个屏幕。所有控件的属性(比如字体大小、颜色等)都可以直接在初始的布局文件中设置。

初始布局

而表示最终状态的布局文件可以只定义最后各控件的位置。

最终布局

之后,由 TransitionManager 计算由初始布局变化到最终布局的路径,并创建流畅的动画。

// Activity.kt
val constraintSet = ConstraintSet()
constraintSet.clone(this, R.layout.detail)

TransitionManager.beginDelayedTransition(myView)  // myView: 当前视图 ConstratintLayout 的 id

constraintSet.apply(myView)

当然 TransitionManager 默认实现的动画是匀速的,我们可以通过自定义 transition 来自定义动画。比如这样:

val transition = ChangeBounds()
transition.interpolator = AnticipateInterpolator(1.0f)
TransitionManager.beginDelayedTransition(constraint, transition)

是不是很简单呢。: )

视频(Youtube):Keyframe Animations with ConstraintLayout and ConstraintSet

日报扩展阅读:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK