《Flutter攻略》之Animation運(yùn)行原理

首先,如果你還不知道什么是Flutter的話,請看這里,簡單講就是Google自己的React Native。它使用的編程語言是Dart,如果不知道什么是Dart的話請看這里。有人可能會問這兩個(gè)東西聽都沒聽過,學(xué)了有用嗎?我的答案是“俺也不知道”。
廢話都多說,下面開始學(xué)習(xí)Flutter的Animation。

Example

我們先來看下最后的運(yùn)行結(jié)果:

基本邏輯就是點(diǎn)擊按鈕,執(zhí)行一個(gè)Animation,然后我們的自定義View就會根據(jù)這個(gè)Animation不斷變化的值來繪制一個(gè)圓形。接下來就看看代碼是怎么實(shí)現(xiàn)的?

class _AnimationPainter extends CustomPainter{

  Animation<double> _repaint ;
  _AnimationPainter({
    Animation<double> repaint
  }):_repaint = repaint,super(repaint:repaint);

  @override
  void paint(Canvas canvas, Size size){
    final Paint paint = new Paint()
      ..color = Colors.red[500].withOpacity(0.25)
      ..strokeWidth = 4.0
      ..style = PaintingStyle.stroke;
    canvas.drawCircle(new Point(size.width/2, size.height/2), _repaint.value, paint);
  }

  @override
  bool shouldRepaint(_AnimationPainter oldDelegate){
    return oldDelegate._repaint != _repaint;
  }
}

首先我們先來自定義一個(gè)Painter,這個(gè)Painter繼承自CustomPainter,構(gòu)造方法中接收一個(gè)Animation對象。在它的paint()方法中使用_repaint.value作為圓形的半徑進(jìn)行繪圖。

接下來我們再看主布局:

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Flutter Demo')
      ),
      body: new Center(
        child: new CustomPaint(
          key:new GlobalKey(),
          foregroundPainter: new _AnimationPainter(
            repaint:_animation
          )
        )
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _startAnimation,
        tooltip: 'startAnimation',
        child: new Icon(Icons.add)
      )
    );
  }

可以看到我們使用了一個(gè)CustomPaint,在Flutter中這算是一個(gè)自定義布局。接著給它構(gòu)造方法中的foregroundPainter參數(shù)傳遞一個(gè)我們之前定義的_AnimationPainter
下面還定義了一個(gè)按鈕,點(diǎn)擊事件為_startAnimation

  void _startAnimation() {
    _animation.forward(from:0.0);
  }

_startAnimation很簡單,就是用來開始一個(gè)動畫的。

OK,到這里布局就講完了,這時(shí)候我們還缺啥?對了,我們還缺一個(gè)Animation對象,下面就定義一個(gè):

  AnimationController _animation = new AnimationController(
    duration: new Duration(seconds: 3),
    lowerBound: 0.0,
    upperBound: 500.0
  );

大家可能會好奇AnimationController又是個(gè)啥玩意?它其實(shí)是Animation的一個(gè)子類,可以用來控制Animation行為。
到這里所有相關(guān)代碼都交代完了,編譯運(yùn)行就能出結(jié)果。
完整代碼:

import 'package:flutter/material.dart';

void main() {
  runApp(
    new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue
      ),
      home: new FlutterDemo()
    )
  );
}

class FlutterDemo extends StatefulWidget {
  FlutterDemo({Key key}) : super(key: key);

  @override
  _FlutterDemoState createState() => new _FlutterDemoState();
}

class _FlutterDemoState extends State<FlutterDemo> {


  AnimationController _animation = new AnimationController(
    duration: new Duration(seconds: 3),
    lowerBound: 0.0,
    upperBound: 500.0
  );
  void _startAnimation() {
    _animation.forward(from:0.0);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Flutter Demo')
      ),
      body: new Center(
        child: new CustomPaint(
          key:new GlobalKey(),
          foregroundPainter: new _AnimationPainter(
            repaint:_animation
          )
        )
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _startAnimation,
        tooltip: 'startAnimation',
        child: new Icon(Icons.add)
      )
    );
  }
}

class _AnimationPainter extends CustomPainter{

  Animation<double> _repaint ;
  _AnimationPainter({
    Animation<double> repaint
  }):_repaint = repaint,super(repaint:repaint);

  @override
  void paint(Canvas canvas, Size size){
    final Paint paint = new Paint()
      ..color = Colors.red[500].withOpacity(0.25)
      ..strokeWidth = 4.0
      ..style = PaintingStyle.stroke;
    canvas.drawCircle(new Point(size.width/2, size.height/2), _repaint.value, paint);
  }

  @override
  bool shouldRepaint(_AnimationPainter oldDelegate){
    return oldDelegate._repaint != _repaint;
  }
}

Animation原理

事物的運(yùn)動狀態(tài)改變是需要外力的,Animation也一樣從靜止到運(yùn)動(動畫執(zhí)行階段),肯定有一股外力的存在,那這股力量就是啥?我們來一探究竟。

在Flutter中的一切都是由flutter engine來驅(qū)動的,看下圖:

由于flutter engine超出了我們討論范圍,我們這里只是假設(shè)它有一個(gè)叫做freshScreen()的方法,用于刷新屏幕。對了,這里的freshScreen就是我們Animation最原始的動力,接下來介紹一個(gè)叫做
Scheduler的類,如下圖:

它是一個(gè)單例,它內(nèi)部有一個(gè)callback列表,用來存儲某些回調(diào),而addFrameCallback方法就是往callback列表添加回調(diào)的。那這里的handleBeginFrame又是干么的呢?當(dāng)flutter engine每調(diào)用一次freshScreen的時(shí)候,就回去調(diào)用Scheduler的handleBeginFrame方法,而在handleBeginFrame中會將callback列表中所有的回調(diào)調(diào)用一遍。并且會給每個(gè)回調(diào)傳遞一個(gè)當(dāng)時(shí)的時(shí)間戳。到這里似乎還沒有Animation什么事,我們繼續(xù)往下看。

到這邊我們應(yīng)該知道系統(tǒng)中有個(gè)叫Schedule的類,你只要調(diào)用它的addFrameCallback方法,向其中添加回調(diào),那么這個(gè)回調(diào)就因?yàn)榻缑娴乃⑿露恢北徽{(diào)用。那么又是誰來使用addFrameCallback呢?答案就是Ticker

Ticker是一個(gè)類似可控的計(jì)時(shí)器,調(diào)用它的start方法后,內(nèi)部會調(diào)用它的_scheduleTick方法,其中會向Schedule中添加名為_tick的方法回調(diào)。而在_tick的方法回調(diào)中會調(diào)用到_onTick方法。這個(gè)_onTick方法是外部傳入的,可自定義其中的內(nèi)容。并且每一次調(diào)用_onTick都會傳入一個(gè)時(shí)間參數(shù),這個(gè)參數(shù)表示從調(diào)用start開始經(jīng)歷的時(shí)間長度。

那么到這里我們知道了,我們不必直接跟Schedule打交道,有一個(gè)更好用的Ticker,我們只要給Ticker傳入一個(gè)回調(diào),就能不斷的拿到一個(gè)△t,這個(gè)△t = now-timeStart。正是這個(gè)△t為我們推來了Animation的大門。

OK,到這里我們知道了Animation動畫執(zhí)行的動力在哪了,接下來看看Animation內(nèi)部是怎么利用Ticker實(shí)現(xiàn)的?

我們回到上面的小例子,拋開自定義的試圖,關(guān)鍵的代碼其實(shí)就兩行,如下:

AnimationController _animation = new AnimationController(
    duration: new Duration(seconds: 3),
    lowerBound: 0.0,
    upperBound: 500.0
  );

_animation.forward(from:0.0);

分別是初始化一個(gè)動畫和開始一個(gè)動畫。那就從這兩行入手,看看底下的源碼實(shí)現(xiàn)。
先看構(gòu)造函數(shù):

  AnimationController({
    double value,
    this.duration,
    this.debugLabel,
    this.lowerBound: 0.0,
    this.upperBound: 1.0
  }) {
    assert(upperBound >= lowerBound);
    _direction = _AnimationDirection.forward;
    _ticker = new Ticker(_tick);
    _internalSetValue(value ?? lowerBound);
  }

這里沒什么,只是初始化一些值,如動畫的值得上下邊界,執(zhí)行時(shí)間和目前值。值得注意的是這里初始化了一個(gè)Ticker,我們看看Ticker的初始化都做了什么?

Ticker(TickerCallback onTick) : _onTick = onTick;

這里初始化了Ticker的_onTick方法,相當(dāng)于傳入了一個(gè)回調(diào)用于Ticker來和Animation_controller交互。具體先不看傳入的這個(gè)_tick方法是啥,后面真正遇到了在做分析。

接著就是forward方法了,它的作用就是讓Animation的值從當(dāng)前值變化到最大值。若不設(shè)置參數(shù),即默認(rèn)為下限值。

  Future<Null> forward({ double from }) {
    _direction = _AnimationDirection.forward;
    if (from != null)
      value = from;
    return animateTo(upperBound);
  }

OK,這是一個(gè)異步的方法,重點(diǎn)在animateTo這個(gè)方法,繼續(xù):

Future<Null> animateTo(double target, { Duration duration, Curve curve: Curves.linear }) {
    Duration simulationDuration = duration;
    if (simulationDuration == null) {
      assert(this.duration != null);
      double range = upperBound - lowerBound;
      double remainingFraction = range.isFinite ? (target - _value).abs() / range : 1.0;
      simulationDuration = this.duration * remainingFraction;
    }
    stop();
    if (simulationDuration == Duration.ZERO) {
      assert(value == target);
      _status = (_direction == _AnimationDirection.forward) ?
        AnimationStatus.completed :
        AnimationStatus.dismissed;
      _checkStatusChanged();
      return new Future<Null>.value();
    }
    assert(simulationDuration > Duration.ZERO);
    assert(!isAnimating);
    return _startSimulation(new _InterpolationSimulation(_value, target, simulationDuration, curve));
  }

雖然這里代碼有些多,但大部分是一些條件判斷和預(yù)處理,這里不需要理會,我們看關(guān)鍵的:

_startSimulation(new _InterpolationSimulation(_value, target, simulationDuration, curve));

這里引入了一個(gè)新的概念Simulation,它其實(shí)相當(dāng)于一個(gè)時(shí)間t和坐標(biāo)x及速度v的關(guān)系,它有一個(gè)x(t)方法,接受一個(gè)參數(shù)t及時(shí)間,返回t時(shí)間時(shí)x的值。在Animation中就是t時(shí)刻的值。而這個(gè)t就是Ticker產(chǎn)生的,我們接著往下看:

  Future<Null> _startSimulation(Simulation simulation) {
    assert(simulation != null);
    assert(!isAnimating);
    _simulation = simulation;
    _lastElapsedDuration = Duration.ZERO;
    _value = simulation.x(0.0).clamp(lowerBound, upperBound);
    Future<Null> result = _ticker.start();
    _status = (_direction == _AnimationDirection.forward) ?
      AnimationStatus.forward :
      AnimationStatus.reverse;
    _checkStatusChanged();
    return result;
  }

這里也是做了一些值得初始化,關(guān)鍵的一句是:

 _ticker.start();

這里啟動了Ticker,我們看看start里面又做了什么?

  Future<Null> start() {
    assert(!isTicking);
    assert(_startTime == null);
    _completer = new Completer<Null>();
    _scheduleTick();
    if (SchedulerBinding.instance.isProducingFrame)
      _startTime = SchedulerBinding.instance.currentFrameTimeStamp;
    return _completer.future;
  }

上面我們主要關(guān)注 _scheduleTick()這個(gè)方法,

  void _scheduleTick({ bool rescheduling: false }) {
    assert(isTicking);
    assert(_animationId == null);
    _animationId = SchedulerBinding.instance.scheduleFrameCallback(_tick, rescheduling: rescheduling);
  }

到這里小伙伴們應(yīng)該已經(jīng)看出來了,這里Ticker將自己的_tick方法回調(diào)注冊到了Scheduler中,一旦注冊完,隨著屏幕的刷新,_tick將會被不停的調(diào)用,

  void _tick(Duration timeStamp) {
    assert(isTicking);
    assert(_animationId != null);
    _animationId = null;

    if (_startTime == null)
      _startTime = timeStamp;

    _onTick(timeStamp - _startTime);

    // The onTick callback may have scheduled another tick already.
    if (isTicking && _animationId == null)
      _scheduleTick(rescheduling: true);
  }

_tick方法中主要做了對時(shí)間的處理,它會將從開始到當(dāng)前的時(shí)間間隔傳給_onTick這個(gè)方法,而這個(gè)方法就是之前AnimationController傳遞進(jìn)來的。及下面的_tick方法:

  void _tick(Duration elapsed) {
    _lastElapsedDuration = elapsed;
    double elapsedInSeconds = elapsed.inMicroseconds.toDouble() / Duration.MICROSECONDS_PER_SECOND;
    _value = _simulation.x(elapsedInSeconds).clamp(lowerBound, upperBound);
    if (_simulation.isDone(elapsedInSeconds)) {
      _status = (_direction == _AnimationDirection.forward) ?
        AnimationStatus.completed :
        AnimationStatus.dismissed;
      stop();
    }
    notifyListeners();
    _checkStatusChanged();
  }

這里應(yīng)該看的很明白了,AnimationController的_tick會被不停的調(diào)用,而AnimationController的值則是由_simulation來根據(jù)時(shí)間計(jì)算得來。接著再調(diào)用notifyListeners()和 _checkStatusChanged()通知監(jiān)聽AnimatinController的對象。
Animation的運(yùn)行原理差不多就是這些,有疑問或?qū)Υ烁信d的可以在我主頁中找到我的微信二維碼,加我好友,我們慢慢聊。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 如果想讓事情變得順利,只有靠自己--夏爾·紀(jì)堯姆 上一章介紹了隱式動畫的概念。隱式動畫是在iOS平臺創(chuàng)建動態(tài)用戶界...
    夜空下最亮的亮點(diǎn)閱讀 1,996評論 0 1
  • >生活和藝術(shù)一樣,最美的永遠(yuǎn)是曲線。--愛德華布爾沃-利頓 在第九章“圖層時(shí)間”中,我們討論了動畫時(shí)間和`CAMe...
    夜空下最亮的亮點(diǎn)閱讀 511評論 0 0
  • *面試心聲:其實(shí)這些題本人都沒怎么背,但是在上海 兩周半 面了大約10家 收到差不多3個(gè)offer,總結(jié)起來就是把...
    Dove_iOS閱讀 27,216評論 30 472
  • 1. 前言 作為Android程序員,或者是想要去模仿一些酷炫的效果,或者是為了實(shí)現(xiàn)視覺的變態(tài)需求,或者是壓抑不住...
    SparkInLee閱讀 19,881評論 7 53
  • 01 我如果可以討你的開心 我愿成為一朵花 讓你摘去我所有花瓣 只留下我注視你的目光 然后雨水蓄滿我的眼眶 三分之...
    守素閱讀 397評論 8 18