Flutter 中使用 Canvas 实现适配图表场景的环形波纹动画求助
Flutter Canvas 光晕扩散动画实现方案
核心逻辑
你要实现的循环向外扩散的半透明光晕效果完全基于Flutter原生Canvas即可实现,不需要引入额外第三方包,不会影响你现有图表包的二次开发逻辑,实现步骤如下:
- 初始化一个循环播放的
AnimationController,根据你想要的动效速度设置动画周期,设置repeat(reverse: false)保证动画循环单向运行 - 动画值区间设为0到1,用来控制光晕的半径、透明度两个核心属性的变化
- 在你现有图表的CustomPainter绘制逻辑中叠加光晕绘制代码即可
核心实现代码
class GlowPainter extends CustomPainter { // 传入AnimationController输出的动画值 final double animationValue; // 光晕中心坐标、基础半径、颜色可根据你的业务需求自定义 final Offset center; final double baseRadius; final Color glowColor; // 同时显示的扩散光晕层数,可自行调整 final int glowLayerCount = 3; GlowPainter({ required this.animationValue, required this.center, required this.baseRadius, required this.glowColor, }) : super(repaint: AlwaysStoppedAnimation(animationValue)); @override void paint(Canvas canvas, Size size) { for (int i = 0; i < glowLayerCount; i++) { // 每层光晕设置偏移进度,避免同时扩散 final layerProgress = (animationValue + i / glowLayerCount) % 1; // 半径随进度从基础值扩大到2倍,可自定义扩大倍数 final currentRadius = baseRadius * (1 + layerProgress); // 透明度随进度从0.6降到0,可自定义初始透明度 final currentOpacity = 0.6 * (1 - layerProgress); final paint = Paint() ..color = glowColor.withOpacity(currentOpacity) ..style = PaintingStyle.fill; canvas.drawCircle(center, currentRadius, paint); } } @override bool shouldRepaint(covariant GlowPainter oldDelegate) { return oldDelegate.animationValue != animationValue; } }
接入说明
你只需要在现有图表的绘制节点中,初始化AnimationController后将动画值传入上述Painter,叠加到你的现有绘制逻辑中即可,不需要修改原有图表包的底层逻辑。
内容的提问来源于stack exchange,提问作者JoaoBaroni
相关产品推荐
相关产品推荐

