【CustomPainter】绘制圆环

说明

绘制一个圆环,进度为0时,显示"圆形"。

效果

源码

  • MyRingPainter
dart 复制代码
class MyRingPainter extends CustomPainter {
  final double progress;

  MyRingPainter({required this.progress});

  @override
  void paint(Canvas canvas, Size size) {
    double _strokeWidth = 12;

    double _halfWidth = size.width / 2;
    Offset _center = Offset(_halfWidth, _halfWidth);

    // 💡关键:找到真正的半径
    // double _radius = _halfWidth; // 绘制的圆环会超过size的范围
    double _radius = _halfWidth - _strokeWidth / 2; // 刚好卡在size范围内

    // 圆环背景色
    // 不填充圆内颜色
    Paint paint = Paint()
      ..color = const Color(0xFFFF6258).withOpacity(0.12)
      ..strokeWidth = _strokeWidth
      ..style = PaintingStyle.stroke;

    canvas.drawCircle(_center, _radius, paint);

    //圆环进度
    Paint linePaint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = _strokeWidth
      ..strokeCap = StrokeCap.round // 线条末端样式为圆形
      ..color = const Color(0xFFFF6258);
    // drawArc : 画弧形,但不连接圆心
    canvas.drawArc(Rect.fromCircle(radius: _radius, center: _center), -pi / 2,
        2 * pi * progress, false, linePaint);
  }

  @override
  bool shouldRepaint(MyRingPainter oldDelegate) {
    return oldDelegate.progress != progress;
  }
}
  • UI渲染
dart 复制代码
           Container(
              width: 244,
              height: 244,
              color: Colors.grey.withOpacity(0.15),
              child: CustomPaint(
                size: const Size(244, 244),
                painter: MyRingPainter(progress: 0.001),
              ),
            )
相关推荐
落叶飘飘s8 小时前
餐饮服务与软件创新的融合:解析海底捞 APP 的 Flutter 鸿蒙开发之路
flutter·华为·harmonyos
起司喵喵11 小时前
Flutter-MacOS桌面OS系统|flutter.+window_manager客户端OS模板
flutter·macos·策略模式
Wuxiaoming13521 小时前
flutter app的logo和splash logo尺寸
flutter
GitLqr1 天前
深入理解 Flutter 架构:从 Widget 到 GPU 像素的全链路解析
flutter·面试·dart
SoaringHeart1 天前
Flutter进阶|最佳实践:组件内阴影实现
前端·flutter
玛艾露贝1 天前
Supabase云同步架构:Flutter应用的数据同步策略
flutter·架构
魔力女仆1 天前
Flutter 复杂拖拽排序实战:同源排序 + 跨容器拖拽完整落地
flutter
杉氧1 天前
状态管理大对决:在 Flutter 实战中如何优雅地管理共享状态?
android·前端·flutter
恋猫de小郭1 天前
Flutter Starling : 用 Swift和 Flutter 写了一个 Linux 桌面系统,震惊我一整年
android·前端·flutter