老孟导读: 在前面的文章中介绍了
《Flutter 动画系列》25 种动画组件超全总结
http://laomengit.com/flutter/module/animated_1/
《Flutter 动画系列》Google 工程师带你选择 Flutter 动画控件:
在项目中动画效果很多时候是几种动画的组合, 比如颜色, 大小, 位移等属性同时变化或者顺序变化, 这篇文章讲解如何实现组合动画
Flutter 中组合动画使用 Interval,Interval 继承自 Curve, 用法如下:
- Animation _sizeAnimation = Tween(begin: 100.0, end: 300.0).animate(CurvedAnimation(
- parent: _animationController, curve: Interval(0.5, 1.0)));
表示_sizeAnimation 动画从 0.5(一半) 开始到结束, 如果动画时长为 6 秒,_sizeAnimation 则从第 3 秒开始.
Interval 中 begin 和 end 参数值的范围是 0.0 到 1.0.
下面实现一个先执行颜色变化, 在执行大小变化, 代码如下:
- class AnimationDemo extends StatefulWidget {
- @override
- State<StatefulWidget> createState() => _AnimationDemo();
- }
- class _AnimationDemo extends State<AnimationDemo>
- with SingleTickerProviderStateMixin {
- AnimationController _animationController;
- Animation _colorAnimation;
- Animation _sizeAnimation;
- @override
- void initState() {
- _animationController =
- AnimationController(duration: Duration(seconds: 5), vsync: this)
- ..addListener((){setState(() {
- });});
- _colorAnimation = ColorTween(begin: Colors.red, end: Colors.blue).animate(
- CurvedAnimation(
- parent: _animationController, curve: Interval(0.0, 0.5)));
- _sizeAnimation = Tween(begin: 100.0, end: 300.0).animate(CurvedAnimation(
- parent: _animationController, curve: Interval(0.5, 1.0)));
- // 开始动画
- _animationController.forward();
- super.initState();
- }
- @override
- Widget build(BuildContext context) {
- return Center(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: <Widget>[
- Container(
- height: _sizeAnimation.value,
- width: _sizeAnimation.value,
- color: _colorAnimation.value),
- ],
- ),
- );
- }
- @override
- void dispose() {
- _animationController.dispose();
- super.dispose();
- }
- }
效果如下:
我们也可以设置同时动画, 只需将 2 个 Interval 的值都改为 Interval(0.0, 1.0).
想象下面的场景, 一个红色的盒子, 动画时长为 6 秒, 前 40% 的时间大小从 100->200, 然后保持 200 不变 20% 的时间, 最后 40% 的时间大小从 200->300, 这种效果通过 TweenSequence 实现, 代码如下:
- _animation = TweenSequence([
- TweenSequenceItem(
- tween: Tween(begin: 100.0, end: 200.0)
- .chain(CurveTween(curve: Curves.easeIn)),
- weight: 40),
- TweenSequenceItem(tween: ConstantTween<double>(200.0), weight: 20),
- TweenSequenceItem(tween: Tween(begin: 200.0, end: 300.0), weight: 40),
- ]).animate(_animationController);
weight 表示每一个 Tween 的权重.
最终效果如下:
交流
来源: https://www.cnblogs.com/mengqd/p/12638021.html