【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),
              ),
            )
相关推荐
来来走走1 小时前
Flutter开发 网络请求
android·flutter
SoaringHeart20 小时前
Flutter进阶:高内存任务的动态并发执行完美实现
前端·flutter
吴Wu涛涛涛涛涛Tao20 小时前
Flutter 实现类似抖音/TikTok 的竖向滑动短视频播放器
android·flutter·ios
猪哥帅过吴彦祖21 小时前
Flutter 插件工作原理深度解析:从 Dart 到 Native 的完整调用链路
android·flutter·ios
叽哥2 天前
flutter学习第 18 节:设备功能调用
android·flutter·ios
来来走走2 天前
Flutter 顶部导航标签组件Tab + TabBar + TabController
android·flutter
程序员老刘2 天前
2025 Google 开发者大会 客户端要点速览
flutter·ai编程·客户端
Wakeup2 天前
当Flutter下载依赖慢,运行在Android上卡Running Gradle task ‘assembleDebug...解决方法
flutter
你听得到112 天前
告别重复造轮子!我从 0 到 1 封装一个搞定全场景的弹窗库!
前端·flutter·性能优化
恋猫de小郭2 天前
Flutter 3.35 发布,快来看看有什么更新吧
android·前端·flutter