You need to enable JavaScript to run this app. Flutter 通过 CustomPaint 绘制自定义透明背景形状问题求助
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 23:36:02