Flutter 動畫基礎

Flutter中的動畫系統基於Animation對象的,widget可以在build函數中讀取Animation對象的當前值, 可以監聽動畫的狀態改變。

flutter動畫實現基於AnimationController對象。所以要先定義:

AnimationController controller =new AnimationController(duration: const Duration(milliseconds: 2000), vsync: this);

其中vsync:this是一個TickerProvider對象,定義了可以發送Ticker對象的接口,它的主要作用是獲取每一幀刷新的通知,相當於給動畫添加了一個動起來的引擎。一般實現(with)SingleTickerProviderStateMixin即可。
定義動畫使用,這裏用:CurvedAnimation來實現

final CurvedAnimation curve = CurvedAnimation(parent: controller, curve: Curves.easeIn);

第一個對象controller傳入定義的controller即可
第二個對象curve 表示動畫曲線函數,類似 Android 動畫的插值器。有一些內置曲線.(一般沒有特殊需求不用傳).

class _Linear extends Curve {
  const _Linear._();

  @override
  double transform(double t) => t;
}
//使用
static const Curve linear = _Linear._();

好了,瞭解上面的之後開始在實際中使用動畫:
1.聲明對象一般在==initState()方法中,要在監聽事件中添加setState((){})==方法不然沒法執行。

 AnimationController controller;
  CurvedAnimation curve;
  @override
  void initState() {
    controller = new AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    curve = CurvedAnimation(parent: controller, curve: Curves.fastOutSlowIn);
    animation.addListener((){
      setState(() {
      });
      Log.i("minePage execute addListener");
    });
    super.initState();
  }

2.聲明之後就可以愉快的使用了.

縮放動畫
 new Container(
         child: new Transform.scale(
         scale: curve.value ,
         child:  new FlutterLogo(size: 100,),
 ),
 )                
旋轉動畫
 new Container(
         child: new Transform.rotate(
         angle: curve.value * 3,
         child:  new FlutterLogo(size: 100,),
   ),
 ),
平移動畫
 new Container(
          child: new Transform.translate(
          		offset:Offset (100.0 * curve.value,0.0),
          child: new FlutterLogo(size: 100,)),
) ,
漸變動畫 (注意這裏是FadeTransition)
 new Container(
         child: new FadeTransition(
         opacity: controller,
         child:  new FlutterTestLogo(),
      ),
 ),

3.最後一步,調用

controller.forward() //或者 controller.reverse();

通過以上代碼,我們可以完成一個基本的動畫效果。git鏈接
在這裏插入圖片描述

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