如何用Flutter的Canvas与CustomPainter绘制带阴影的Tooltip弹窗
修复Flutter CustomPainter实现带阴影Tooltip弹窗的问题
当前代码存在几个核心问题导致效果不符:
- 使用描边模式而非填充模式,无法呈现实心弹窗背景
- 箭头与圆角矩形分开绘制,无法统一添加阴影效果
- 未设置阴影相关参数
以下是修复后的完整代码:
class CustomStyleArrow extends CustomPainter { @override void paint(Canvas canvas, Size size) { const double triangleH = 10; const double triangleW = 25.0; final double width = size.width; final double height = size.height; final borderRadius = BorderRadius.circular(4); // 创建合并了圆角矩形和箭头的完整闭合路径 final path = Path() // 添加圆角矩形路径 ..addRRect(borderRadius.toRRect(Rect.fromLTRB(0, 0, width, height))) // 移动到箭头左端点 ..moveTo(width / 2 - triangleW / 2, height) // 绘制箭头左斜边到顶点 ..lineTo(width / 2, height + triangleH) // 绘制箭头右斜边到右端点 ..lineTo(width / 2 + triangleW / 2, height) // 闭合路径,确保图形完整无缺口 ..close(); // 填充画笔:设置背景色与阴影 final fillPaint = Paint() ..color = Colors.white // 可根据需求修改背景色 ..style = PaintingStyle.fill ..shadowColor = Colors.black.withOpacity(0.3) ..blurRadius = 8; // 阴影模糊程度,数值越大阴影越扩散 canvas.drawPath(path, fillPaint); // 可选:添加描边效果,增强边框质感 final strokePaint = Paint() ..color = Colors.grey.shade300 ..strokeWidth = 1 ..style = PaintingStyle.stroke; canvas.drawPath(path, strokePaint); } @override bool shouldRepaint(CustomPainter oldDelegate) => false; }
关键修改说明
- 路径合并:将圆角矩形与箭头路径合并为一个整体,确保填充和阴影能覆盖整个Tooltip区域
- 填充模式:将
PaintingStyle改为fill,实现实心背景效果 - 阴影实现:通过
shadowColor和blurRadius属性添加阴影,阴影会跟随整个路径形状 - 路径闭合:使用
close()方法确保路径完全闭合,避免图形出现缺口
内容的提问来源于stack exchange,提问作者Aditya Patil
相关产品推荐
相关产品推荐

