Flutter路径动画插件path_animator的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter路径动画插件path_animator的使用

Path Animator

A flutter package to draw path with animation on canvas.

Show some ❤️ and ⭐ the repo

Features

  • ✅ Animated Path Drawing

Demo

Demo

Getting Started

包含插件到项目中

pubspec.yaml 文件中添加 path_animator 插件:

dependencies:
  path_animator: <latest version>

运行 pub get 来获取包。

构建动画路径

build 函数创建动画路径并返回它。

final animatedPath = PathAnimator.build(
    path: path,
    animationPercent: controller.value,
);

返回的动画路径然后用于在画布上绘制路径。

canvas.drawPath(animatedPath, paint);

Example

完整示例代码

import 'package:flutter/material.dart';
import 'package:path_animator/path_animator.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Path Animator',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Path Animator'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  AnimationController? _controller;

  @override
  void initState() {
    _controller = AnimationController(
      duration: const Duration(seconds: 1),
      vsync: this,
    );

    WidgetsBinding.instance!.addPostFrameCallback((_) {
      _controller!.forward();
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: CustomPaint(
        child: const SizedBox(width: 500, height: 500),
        painter: _MyCustomPainter(
          controller: _controller!,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _controller!.reset();
          _controller!.forward();
        },
        tooltip: 'Reset',
        child: const Icon(Icons.refresh),
      ),
    );
  }
}

class _MyCustomPainter extends CustomPainter {
  _MyCustomPainter({
    required this.controller,
  }) : super(repaint: controller);

  final AnimationController controller;

  @override
  void paint(Canvas canvas, Size size) {
    final path = Path();
    path.moveTo(0.0, size.height * 0.25);
    path.lineTo(size.width * 0.25, size.height * 0.75);
    path.lineTo(size.width * 0.75, size.height * 0.75);
    path.lineTo(size.width, size.height * 0.25);
    path.close();

    // draw graph
    final path1 = Path();
    final animatedPath = PathAnimator.build(
      path: path,
      animationPercent: controller.value,
    );

    final paint = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;

    canvas.drawPath(animatedPath, paint);
  }

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

Project Created & Maintained By

Divyanshu Shekhar

GitHub followers

Contributions

Contributions are welcomed!

If you feel that a hook is missing, feel free to open a pull-request.

For a custom-hook to be merged, you will need to do the following:

  • Describe the use-case.
  • Open an issue explaining why we need this hook, how to use it, etc. This is important as a hook will not get merged if the hook doesn’t appeal to a large number of people.
  • If your hook is rejected, don’t worry! A rejection doesn’t mean that it won’t be merged later in the future if more people show an interest in it. In the meantime, feel free to publish your hook as a package on https://pub.dev.
  • A hook will not be merged unless fully tested, to avoid breaking it inadvertently in the future.

Stargazers

Stargazers repo roster for [@DevsOnFlutter](/user/DevsOnFlutter)/path_animator

Forkers

Forkers repo roster for [@DevsOnFlutter](/user/DevsOnFlutter)/path_animator

Copyright & License

Code and documentation Copyright © 2021 DevsOnFlutter. Code released under the BSD 3-Clause License.


更多关于Flutter路径动画插件path_animator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter路径动画插件path_animator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter中使用path_animator插件来实现路径动画的示例代码。path_animator插件允许你沿着一个预定义的路径对Widget进行动画处理。首先,确保你的pubspec.yaml文件中已经添加了path_animator依赖:

dependencies:
  flutter:
    sdk: flutter
  path_animator: ^x.y.z  # 请替换为最新版本号

然后,运行flutter pub get来安装依赖。

下面是一个完整的示例代码,展示如何使用path_animator

import 'package:flutter/material.dart';
import 'package:path_animator/path_animator.dart';
import 'dart:math' as math;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Path Animator Example'),
        ),
        body: Center(
          child: PathAnimationExample(),
        ),
      ),
    );
  }
}

class PathAnimationExample extends StatefulWidget {
  @override
  _PathAnimationExampleState createState() => _PathAnimationExampleState();
}

class _PathAnimationExampleState extends State<PathAnimationExample> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat(reverse: true);

    _animation = Tween<double>(begin: 0, end: 1).animate(_controller);
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      child: Container(
        width: 50,
        height: 50,
        color: Colors.blue,
      ),
      builder: (context, child) {
        return PathAnimator(
          path: Path()
            ..moveTo(0, 0)
            ..quadraticBezierTo(
              200, -100,
              400, 0,
            ),
          animation: _animation,
          child: child,
          duration: _controller.duration,
          alignment: Alignment.center,
        );
      },
    );
  }
}

代码解释

  1. 依赖导入

    • 导入flutter/material.dart用于基础UI组件。
    • 导入path_animator/path_animator.dart用于路径动画。
  2. 主应用

    • MyApp是一个简单的Flutter应用,包含一个Scaffold和一个中心对齐的PathAnimationExample组件。
  3. 路径动画组件

    • PathAnimationExample是一个有状态的组件,用于管理动画控制器和动画。
    • initState方法中,初始化AnimationControllerTween<double>动画。
    • dispose方法中释放动画控制器资源。
  4. 构建动画

    • 使用AnimatedBuilder来监听动画值的变化。
    • PathAnimator组件接受一个路径(Path对象)和动画值。路径通过Path()对象定义,这里使用了一个二次贝塞尔曲线(quadraticBezierTo)。
    • child参数是要进行动画处理的Widget,这里是一个蓝色的Container
    • alignment参数决定了子Widget在路径上的对齐方式。

这个示例展示了如何使用path_animator沿着一个二次贝塞尔曲线移动一个蓝色的方块。你可以根据需要调整路径和动画参数,以实现不同的动画效果。

回到顶部