flutter 基础 —— CustomPaint 动画效果
路径动画
示例:

代码
//路径动画
var path = Path()
..moveTo(50, 50)
..lineTo(100, 100)
..lineTo(200, 90);
var rect1 = Rect.fromCircle(center: Offset(80, 450), radius: 60);
// 中间断开了
path.arcTo(rect1, 0, pi, true);
//由于前面断开了,所以总共有两段路径
ui.PathMetrics pathMetrics = path.computeMetrics();
if (_controller.value < 0.5) {
var m = pathMetrics.first;
Path extPath = m.extractPath(0, m.length * _controller.value * 2);
canvas.drawPath(
extPath,
Paint()
..strokeWidth = 5
..style = PaintingStyle.stroke
..color = Colors.red);
} else {
var m = pathMetrics.last;
Path extPath = m.extractPath(0, m.length * (_controller.value - 0.5) * 2);
canvas.drawPath(
extPath,
Paint()
..strokeWidth = 5
..style = PaintingStyle.stroke
..color = Colors.red);
}
动画串联执行
示例:

代码:
var rect = Rect.fromCircle(center: Offset(200, 200), radius: 50 * _controller.value);
var path = Path()
..moveTo(50, 50)
..lineTo(150, 150)
..lineTo(150, 300)
..lineTo(150, 400)
..arcTo(rect, 0, 3.14 * 2, true);
var paint = Paint()
..strokeWidth = 2
..color = Colors.green
..style = PaintingStyle.stroke;
var pathMetrics = path.computeMetrics();
List<PathMetric> metrics = [];
for (var metric in pathMetrics) {
metrics.add(metric);
}
metrics.asMap().forEach((index, metric) {
var animate = Tween(begin: 0.0, end: 1.0)
.animate(CurvedAnimation(parent: _controller,
curve: Interval(index/metrics.length, 1, curve: Curves.fastOutSlowIn)));
var path = metric.extractPath(0, metric.length * animate.value);
canvas.drawPath(path, paint);
});
旋转动画
示例:

代码
//旋转动画
canvas.save();
canvas.translate(100, 100);
final radians = _controller.value * 2 * pi;
canvas.rotate(radians);
canvas.translate(-100, -100);
canvas.drawLine(
Offset(100, 100),
Offset(130, 196),
Paint()
..strokeWidth = 5
..color = Colors.green);
canvas.restore();
2333
浙公网安备 33010602011771号