【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),
              ),
            )
相关推荐
小a杰.31 分钟前
Flutter 与 AI 深度集成指南:从基础实现到高级应用
人工智能·flutter
程序员老刘7 小时前
跨平台开发地图:客户端技术选型指南 | 2025年12月
flutter·客户端
一名普通的程序员8 小时前
使用 Flutter Pay 插件实现 Apple Pay 和 Google Pay 的完整指南
flutter
麦客奥德彪9 小时前
Flutter riverpod 对应Android开发概念理解
flutter
tangweiguo0305198710 小时前
Kotlin vs Dart vs Swift:语法对比全解
flutter
feelingHy10 小时前
GetX 状态管理实践
flutter
tangweiguo0305198711 小时前
Flutter多品牌应用架构实战:从配置驱动到编译部署的完整解决方案
flutter
Bryce李小白11 小时前
FlutterBoost适配Flutter3.38.4版本生成补丁包
flutter
tangweiguo0305198712 小时前
Flutter Packages 设计与实践:构建可维护的模块化应用
flutter
小a杰.13 小时前
Flutter 的编译技术核心
flutter