《Flutter 動畫系列》組合動畫

老孟導讀:在前面的文章中介紹了

《Flutter 動畫系列》25種動畫組件超全總結

《Flutter 動畫系列》Google工程師帶你選擇Flutter動畫控件:

在項目中動畫效果很多時候是幾種動畫的組合,比如顏色、大小、位移等屬性同時變化或者順序變化,這篇文章講解如何實現組合動畫

Flutter中組合動畫使用IntervalInterval繼承自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秒開始。

Intervalbeginend參數值的範圍是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的權重。

最終效果如下:

交流

如果你對Flutter還有疑問或者技術方面的疑惑,歡迎加入Flutter交流羣(微信:laomengit)。

同時也歡迎關注我的Flutter公衆號【老孟程序員】,公衆號首發Flutter的相關內容。

Flutter地址:http://laomengit.com 裏面包含160多個組件的詳細用法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章