如何为抖动中的路径设置动画?

时间:2018-06-21 23:09:30

标签: flutter

我想实现路径动画效果,如此处所示:

This animation (I couldn't include it because the gif is too big)

我只想在地图动画上实现路径,我知道我需要使用堆叠的地图,放置地图,然后使用Painter绘制这样的路径,但是我该如何对其进行动画处理?

3 个答案:

答案 0 :(得分:3)

您实际上不需要堆栈;您可以在地图图像上使用前景色。要为CustomPainter设置动画,请将AnimationController传递到其构造函数中,还传递给super构造函数。在paint中,使用动画的value决定绘制的路径。例如,如果value为0.25,则仅绘制路径的前25%。

class AnimatedPainter extends CustomPainter {
  final Animation<double> _animation;

  AnimatedPainter(this._animation) : super(repaint: _animation);

  @override
  void paint(Canvas canvas, Size size) {
    // _animation.value has a value between 0.0 and 1.0
    // use this to draw the first X% of the path
  }

  @override
  bool shouldRepaint(AnimatedPainter oldDelegate) {
    return true;
  }
}

class PainterDemo extends StatefulWidget {
  @override
  PainterDemoState createState() => new PainterDemoState();
}

class PainterDemoState extends State<PainterDemo>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(
      vsync: this,
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _startAnimation() {
    _controller.stop();
    _controller.reset();
    _controller.repeat(
      period: Duration(seconds: 5),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: const Text('Animated Paint')),
      body: new CustomPaint(
        foregroundPainter: new AnimatedPainter(_controller),
        child: new SizedBox(
          // doesn't have to be a SizedBox - could be the Map image
          width: 200.0,
          height: 200.0,
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _startAnimation,
        child: new Icon(Icons.play_arrow),
      ),
    );
  }
}

void main() {
  runApp(
    new MaterialApp(
      home: new PainterDemo(),
    ),
  );
}

大概您将具有定义路径的坐标列表。假定一些点列表,您将使用类似以下内容绘制完整的路径:

if (points.isEmpty) return;
Path path = Path();
Offset origin = points[0];
path.moveTo(origin.dx, origin.dy);
for (Offset o in points) {
  path.lineTo(o.dx, o.dy);
}
canvas.drawPath(
  path,
  Paint()
    ..color = Colors.orange
    ..style = PaintingStyle.stroke
    ..strokeWidth = 4.0,
);

value小于1.0时,您需要设计一种绘制路径不到100%的方法。例如,当value为0.25时,您可能只将点的前四分之一添加到路径中。如果您的路径由相对较少的点组成,那么如果您计算路径的总 length 并仅绘制路径的第一部分,而这些部分的总和就是四分之一,那么您可能会获得最流畅的动画总长度。

答案 1 :(得分:0)

我为此创建了一个库:drawing_animation

您只需要向小部件提供Path对象:

此图像输出结果:imgur

import 'package:drawing_animation/drawing_animation.dart';
//...
List<Paths> dottedPathArray = ...;
bool run = true;
//...

AnimatedDrawing.paths(
    this.dottedPathArray,
    run: this.run,
    animationOrder: PathOrders.original,
    duration: new Duration(seconds: 2),
    lineAnimation: LineAnimation.oneByOne,
    animationCurve: Curves.linear,
    onFinish: () => setState(() {
      this.run = false;
    }),
)),


答案 2 :(得分:0)

我知道这个问题的答案可以接受,但是我想为这个问题提供替代解决方案。

首先,对于以下情况,从各个点创建自定义路径并不是最佳选择:

  • 计算每个段的长度并非易事
  • 以小幅度均匀地分配步骤动画既困难又费力
  • 不适用于二次/贝塞尔曲线段

就像在is this path tracing method的旧版Android中一样,Flutter也存在非常相似的PathMetrics

在此问题的公认答案的基础上,这是一种动画化任何路径的通用方法。


因此,给定路径和动画百分比,我们需要从头开始提取路径直到该百分比:

Path createAnimatedPath(
  Path originalPath,
  double animationPercent,
) {
  // ComputeMetrics can only be iterated once!
  final totalLength = originalPath
      .computeMetrics()
      .fold(0.0, (double prev, PathMetric metric) => prev + metric.length);

  final currentLength = totalLength * animationPercent;

  return extractPathUntilLength(originalPath, currentLength);
}

所以现在我只需要提取一条路径直到给定的长度(而不是百分比)即可。我们需要将所有现有路径合并到一定距离。然后将最后一个路径段的一部分添加到此现有路径中。

这样做非常简单。

Path extractPathUntilLength(
  Path originalPath,
  double length,
) {
  var currentLength = 0.0;

  final path = new Path();

  var metricsIterator = originalPath.computeMetrics().iterator;

  while (metricsIterator.moveNext()) {
    var metric = metricsIterator.current;

    var nextLength = currentLength + metric.length;

    final isLastSegment = nextLength > length;
    if (isLastSegment) {
      final remainingLength = length - currentLength;
      final pathSegment = metric.extractPath(0.0, remainingLength);

      path.addPath(pathSegment, Offset.zero);
      break;
    } else {
      // There might be a more efficient way of extracting an entire path
      final pathSegment = metric.extractPath(0.0, metric.length);
      path.addPath(pathSegment, Offset.zero);
    }

    currentLength = nextLength;
  }

  return path;
}

整个示例所需的其余代码:

void main() => runApp(
  new MaterialApp(
    home: new AnimatedPathDemo(),
  ),
);

class AnimatedPathPainter extends CustomPainter {
  final Animation<double> _animation;

  AnimatedPathPainter(this._animation) : super(repaint: _animation);

  Path _createAnyPath(Size size) {
    return Path()
      ..moveTo(size.height / 4, size.height / 4)
      ..lineTo(size.height, size.width / 2)
      ..lineTo(size.height / 2, size.width)
      ..quadraticBezierTo(size.height / 2, 100, size.width, size.height);
  }

  @override
  void paint(Canvas canvas, Size size) {
    final animationPercent = this._animation.value;

    print("Painting + ${animationPercent} - ${size}");

    final path = createAnimatedPath(_createAnyPath(size), animationPercent);

    final Paint paint = Paint();
    paint.color = Colors.amberAccent;
    paint.style = PaintingStyle.stroke;
    paint.strokeWidth = 10.0;

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

class AnimatedPathDemo extends StatefulWidget {
  @override
  _AnimatedPathDemoState createState() => _AnimatedPathDemoState();
}

class _AnimatedPathDemoState extends State<AnimatedPathDemo>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;

  void _startAnimation() {
    _controller.stop();
    _controller.reset();
    _controller.repeat(
      period: Duration(seconds: 5),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: const Text('Animated Paint')),
      body: SizedBox(
        height: 300,
        width: 300,
        child: new CustomPaint(
          painter: new AnimatedPathPainter(_controller),
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _startAnimation,
        child: new Icon(Icons.play_arrow),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(
      vsync: this,
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}