6

如何玩转 Flutter 动画

 3 years ago
source link: https://www.infoq.cn/article/9wzqmu3pb83lk1WJEzhy
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.

在使用手机的过程中动画效果随处可见,动画设计可以很好地提升用户体验,在 iOS、Android 平台都有各自实现动画效果的方式。在 Flutter 中,动画也是必不可少的内容,并且体验可以达到接近原生的效果。

1 Flutter 动画基本概念

1.1 Animation

  • Flutter 中的动画基于 Animation 对象,它是一个抽象类,保存了当前动画的值和状态;

  • Animation 对象在一段时间内依次生成一个区间之间值,比较常见的类型是Animation<double>,其他的还有Animation<Color> 或 Animation<Size>;

  • Animation 对象和 UI 渲染是无关的,UI 对象通过读取 Animation 对象的值和监听状态变化运行 build 函数,然后渲染到屏幕上形成动画效果。

1.2 AnimationController

AnimationController 是 Animation<double> 的子类,具有控制动画的启动、暂停、结束等方法:

  • AnimationController 会生成一系列的值,数字的产生与屏幕刷新有关,因此每秒钟通常会产生60个数字,(默认情况下,AnimationController 在给定的时间段内会线性的生成从0.0到1.0之间的数字);

  • 在生成每个数字后,每个 Animation 对象调用添加的 Listener 对象。

AnimationController 需要一个 vsync 必传参数,vsync 对象会绑定动画的定时器到一个可视的 widget,它的作用是避免动画相关 UI 不在当前屏幕时消耗资源:

  • 当 widget 不显示时,动画定时器将会暂停;

  • 当 widget 再次显示时,动画定时器重新恢复执行;

  • 如果要使用自定义的 State 对象作为 vsync 时,需要包含 TickerProviderStateMixin;

AnimationController 控制动画的方法:

  • forward:向前执行动画;

  • reverse:反向执行动画;

  • stop:停止动画;

代码示例:

AnimationController controller = AnimationController(    duration: const Duration(seconds: 5),    vsync: this);

复制代码

1.3 CurvedAnimation

CurvedAnimation 是 Animation< double > 的子类,它可以将 AnimationController 定义为一个非线性曲线动画。

curve 参数对象的有一些常量 Curves(和 Color 类型有一些 Colors 是一样的)可以供我们直接使用,例如:linear、easeIn、easeOut、easeInToLinear 等等。

代码示例:

CurvedAnimation curvedAnimation = CurvedAnimation(    parent: controller,    curve: Curves.linear);

复制代码

1.4 Tween


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK