Flutter 通过 CustomPaint 绘制自定义透明背景形状问题求助
解决方案
你当前使用手动描点生成的贝塞尔曲线存在对称性差、精度不足的问题,直接通过对称计算生成路径即可得到完美的四叶草形状,可直接用作按钮的半透明背景。
使用前需导入dart:math库:import 'dart:math';
完整实现代码
调用示例
// 用作按钮背景,按需调整大小即可 SizedBox( width: 40, height: 40, child: CustomPaint( painter: CloverPainter( bgColor: Colors.white.withOpacity(0.7), // 按需调整背景色和透明度 ), child: Icon(Icons.close, color: Colors.black), // 按钮内容可直接放在child里 ), )
自定义Painter实现
class CloverPainter extends CustomPainter { final Color bgColor; const CloverPainter({required this.bgColor}); @override void paint(Canvas canvas, Size size) { final paint = Paint() ..style = PaintingStyle.fill ..isAntiAlias = true ..color = bgColor; final path = Path(); final centerX = size.width / 2; final centerY = size.height / 2; final radius = min(size.width, size.height) / 2 * 0.8; // 生成四个对称的花瓣,自动保证形状完美对称 for (int i = 0; i < 4; i++) { final angle = i * pi / 2; final dx = centerX + cos(angle) * radius * 0.5; final dy = centerY + sin(angle) * radius * 0.5; path.addOval(Rect.fromCircle(center: Offset(dx, dy), radius: radius * 0.6)); } path.fillType = PathFillType.evenOdd; canvas.drawPath(path, paint); } @override bool shouldRepaint(covariant CloverPainter oldDelegate) { return bgColor != oldDelegate.bgColor; } }
如果需要调整花瓣的大小和形状,可以修改radius参数后的系数即可,调整后形状依然保持对称,不会出现变形问题。如果只需要半个四叶草用作角落的按钮背景,可通过裁剪或者调整循环次数和角度实现。
内容的提问来源于stack exchange,提问作者Gbenga B Ayannuga
相关产品推荐
相关产品推荐

