You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何绘制图示样式的图形?Flutter绘图实现求助

Flutter 实现双圆连接图形的两种方案

你提到的这种两个圆形中间相连的图形,有两种靠谱的实现方式,不用纠结:

方案一:自定义 CustomPainter(灵活可控)

这是最适合自定义形状的方式,直接通过画布绘制完整图形:

  1. 先定义一个 CustomPainter 子类,实现绘制逻辑:
class ConnectedCirclesPainter extends CustomPainter {
  final Color fillColor;
  final double circleRadius;

  ConnectedCirclesPainter({required this.fillColor, required this.circleRadius});

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..color = fillColor..style = PaintingStyle.fill;
    
    // 绘制左侧圆形
    canvas.drawCircle(Offset(circleRadius, size.height / 2), circleRadius, paint);
    // 绘制右侧圆形
    canvas.drawCircle(Offset(size.width - circleRadius, size.height / 2), circleRadius, paint);
    // 绘制中间连接矩形(刚好衔接两个圆的边缘)
    final connectRect = Rect.fromLTWH(
      circleRadius,
      (size.height / 2) - circleRadius,
      size.width - 2 * circleRadius,
      2 * circleRadius,
    );
    canvas.drawRect(connectRect, paint);
  }

  @override
  bool shouldRepaint(covariant ConnectedCirclesPainter oldDelegate) {
    return oldDelegate.fillColor != fillColor || oldDelegate.circleRadius != circleRadius;
  }
}
  1. 使用时用 CustomPaint 组件包裹:
CustomPaint(
  size: const Size(220, 60), // 按需调整整体尺寸
  painter: ConnectedCirclesPainter(
    fillColor: Colors.blueAccent,
    circleRadius: 30,
  ),
)

这种方式能精准控制图形的每一部分,比如要给中间加圆角、调整间隙都很方便。

方案二:组合现有组件(快速实现)

如果不想写自定义绘制代码,用 Stack 组合容器也能搞定:

Stack(
  alignment: Alignment.center,
  children: [
    // 中间的连接矩形(宽度要适配两个圆的间距,让圆覆盖住两端)
    Container(
      width: 160,
      height: 60,
      color: Colors.blueAccent,
    ),
    // 左右两个圆形容器
    Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Container(
          width: 60,
          height: 60,
          decoration: const BoxDecoration(
            color: Colors.blueAccent,
            shape: BoxShape.circle,
          ),
        ),
        Container(
          width: 60,
          height: 60,
          decoration: const BoxDecoration(
            color: Colors.blueAccent,
            shape: BoxShape.circle,
          ),
        ),
      ],
    ),
  ],
)

原理很简单:先画中间的矩形,再把两个圆放在左右两边,让圆覆盖住矩形的两端,视觉上就变成了相连的形状。

内容的提问来源于stack exchange,提问作者AmirHossein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:53:13