《Flutter攻略》之Animation运行原理

《《Flutter攻略》之Animation运行原理》

首先,如果你还不知道什么是Flutter的话,请看这里,简单讲就是Google自己的React Native。它使用的编程语言是Dart,如果不知道什么是Dart的话请看这里。有人可能会问这两个东西听都没听过,学了有用吗?我的答案是“俺也不知道”。
废话都多说,下面开始学习Flutter的Animation。

《《Flutter攻略》之Animation运行原理》

Example

我们先来看下最后的运行结果:

《《Flutter攻略》之Animation运行原理》

基本逻辑就是点击按钮,执行一个Animation,然后我们的自定义View就会根据这个Animation不断变化的值来绘制一个圆形。接下来就看看代码是怎么实现的?

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;
  }
}

首先我们先来自定义一个Painter,这个Painter继承自CustomPainter,构造方法中接收一个Animation对象。在它的paint()方法中使用_repaint.value作为圆形的半径进行绘图。

接下来我们再看主布局:

  @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)
      )
    );
  }

可以看到我们使用了一个CustomPaint,在Flutter中这算是一个自定义布局。接着给它构造方法中的foregroundPainter参数传递一个我们之前定义的_AnimationPainter
下面还定义了一个按钮,点击事件为_startAnimation

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

_startAnimation很简单,就是用来开始一个动画的。

OK,到这里布局就讲完了,这时候我们还缺啥?对了,我们还缺一个Animation对象,下面就定义一个:

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

大家可能会好奇AnimationController又是个啥玩意?它其实是Animation的一个子类,可以用来控制Animation行为。
到这里所有相关代码都交代完了,编译运行就能出结果。
完整代码:

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原理

事物的运动状态改变是需要外力的,Animation也一样从静止到运动(动画执行阶段),肯定有一股外力的存在,那这股力量就是啥?我们来一探究竟。

在Flutter中的一切都是由flutter engine来驱动的,看下图:

《《Flutter攻略》之Animation运行原理》

由于flutter engine超出了我们讨论范围,我们这里只是假设它有一个叫做freshScreen()的方法,用于刷新屏幕。对了,这里的freshScreen就是我们Animation最原始的动力,接下来介绍一个叫做
Scheduler的类,如下图:

《《Flutter攻略》之Animation运行原理》

它是一个单例,它内部有一个callback列表,用来存储某些回调,而addFrameCallback方法就是往callback列表添加回调的。那这里的handleBeginFrame又是干么的呢?当flutter engine每调用一次freshScreen的时候,就回去调用Scheduler的handleBeginFrame方法,而在handleBeginFrame中会将callback列表中所有的回调调用一遍。并且会给每个回调传递一个当时的时间戳。到这里似乎还没有Animation什么事,我们继续往下看。

到这边我们应该知道系统中有个叫Schedule的类,你只要调用它的addFrameCallback方法,向其中添加回调,那么这个回调就因为界面的刷新而一直被调用。那么又是谁来使用addFrameCallback呢?答案就是Ticker

《《Flutter攻略》之Animation运行原理》

Ticker是一个类似可控的计时器,调用它的start方法后,内部会调用它的_scheduleTick方法,其中会向Schedule中添加名为_tick的方法回调。而在_tick的方法回调中会调用到_onTick方法。这个_onTick方法是外部传入的,可自定义其中的内容。并且每一次调用_onTick都会传入一个时间参数,这个参数表示从调用start开始经历的时间长度。

那么到这里我们知道了,我们不必直接跟Schedule打交道,有一个更好用的Ticker,我们只要给Ticker传入一个回调,就能不断的拿到一个△t,这个△t = now-timeStart。正是这个△t为我们推来了Animation的大门。

OK,到这里我们知道了Animation动画执行的动力在哪了,接下来看看Animation内部是怎么利用Ticker实现的?

我们回到上面的小例子,抛开自定义的试图,关键的代码其实就两行,如下:

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

_animation.forward(from:0.0);

分别是初始化一个动画和开始一个动画。那就从这两行入手,看看底下的源码实现。
先看构造函数:

  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);
  }

这里没什么,只是初始化一些值,如动画的值得上下边界,执行时间和目前值。值得注意的是这里初始化了一个Ticker,我们看看Ticker的初始化都做了什么?

Ticker(TickerCallback onTick) : _onTick = onTick;

这里初始化了Ticker的_onTick方法,相当于传入了一个回调用于Ticker来和Animation_controller交互。具体先不看传入的这个_tick方法是啥,后面真正遇到了在做分析。

接着就是forward方法了,它的作用就是让Animation的值从当前值变化到最大值。若不设置参数,即默认为下限值。

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

OK,这是一个异步的方法,重点在animateTo这个方法,继续:

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));
  }

虽然这里代码有些多,但大部分是一些条件判断和预处理,这里不需要理会,我们看关键的:

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

这里引入了一个新的概念Simulation,它其实相当于一个时间t和坐标x及速度v的关系,它有一个x(t)方法,接受一个参数t及时间,返回t时间时x的值。在Animation中就是t时刻的值。而这个t就是Ticker产生的,我们接着往下看:

  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;
  }

这里也是做了一些值得初始化,关键的一句是:

 _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;
  }

上面我们主要关注 _scheduleTick()这个方法,

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

到这里小伙伴们应该已经看出来了,这里Ticker将自己的_tick方法回调注册到了Scheduler中,一旦注册完,随着屏幕的刷新,_tick将会被不停的调用,

  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方法中主要做了对时间的处理,它会将从开始到当前的时间间隔传给_onTick这个方法,而这个方法就是之前AnimationController传递进来的。及下面的_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();
  }

这里应该看的很明白了,AnimationController的_tick会被不停的调用,而AnimationController的值则是由_simulation来根据时间计算得来。接着再调用notifyListeners()和 _checkStatusChanged()通知监听AnimatinController的对象。
Animation的运行原理差不多就是这些,有疑问或对此感兴的可以在我主页中找到我的微信二维码,加我好友,我们慢慢聊。

《《Flutter攻略》之Animation运行原理》

    原文作者:_番茄沙司
    原文地址: https://www.jianshu.com/p/ddca0cc340d5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞