【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),
              ),
            )
相关推荐
孤鸿玉15 小时前
Fluter InteractiveViewer 与ScrollView滑动冲突问题解决
flutter
叽哥21 小时前
Flutter Riverpod上手指南
android·flutter·ios
BG2 天前
Flutter 简仿Excel表格组件介绍
flutter
zhangmeng2 天前
FlutterBoost在iOS26真机运行崩溃问题
flutter·app·swift
恋猫de小郭2 天前
对于普通程序员来说 AI 是什么?AI 究竟用的是什么?
前端·flutter·ai编程
卡尔特斯2 天前
Flutter A GlobalKey was used multipletimes inside one widget'schild list.The ...
flutter
w_y_fan2 天前
Flutter 滚动组件总结
前端·flutter
醉过才知酒浓2 天前
Flutter Getx 的页面传参
flutter
火柴就是我3 天前
flutter 之真手势冲突处理
android·flutter
Speed1233 天前
`mockito` 的核心“打桩”规则
flutter·dart