我使用canvas.drawline来显示一条线,但我希望用户能够看到它从一个点绘制到另一个点,如果可能,还可以控制动画的持续时间。
(类似于进度条,但这是我的自定义小部件)
最佳答案
可以使用AnimationController来控制动画持续时间。
要绘制“一步一步”线,可以使用Tween(开始值和结束值之间的线性插值)。
然后您只需要将当前进度传递给线绘制器,并在调用paint()
时计算每个canvas.drawLine
上的新宽度/高度。
工作示例:
import 'package:flutter/material.dart';
class Line extends StatefulWidget {
@override
State<StatefulWidget> createState() => _LineState();
}
class _LineState extends State<Line> with SingleTickerProviderStateMixin {
double _progress = 0.0;
Animation<double> animation;
@override
void initState() {
super.initState();
var controller = AnimationController(duration: Duration(milliseconds: 3000), vsync: this);
animation = Tween(begin: 1.0, end: 0.0).animate(controller)
..addListener(() {
setState(() {
_progress = animation.value;
});
});
controller.forward();
}
@override
Widget build(BuildContext context) {
return CustomPaint(painter: LinePainter(_progress));
}
}
class LinePainter extends CustomPainter {
Paint _paint;
double _progress;
LinePainter(this._progress) {
_paint = Paint()
..color = Colors.green
..strokeWidth = 8.0;
}
@override
void paint(Canvas canvas, Size size) {
canvas.drawLine(Offset(0.0, 0.0), Offset(size.width - size.width * _progress, size.height - size.height * _progress), _paint);
}
@override
bool shouldRepaint(LinePainter oldDelegate) {
return oldDelegate._progress != _progress;
}
}
然后这样使用:
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _HomeState();
}
}
class _HomeState extends State<Home> {
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('Line animation'),
leading: new Icon(Icons.insert_emoticon),
),
backgroundColor: Colors.white,
body: SizedBox(height: 200, width: 200, child: Line()),
);
}
}
该线将在3秒内从
0,0
绘制到200,200
大小框中。结果: