【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 for OpenHarmony 实战:打造天气预报应用
开发语言·网络·jvm·数据库·flutter·harmonyos
小白郭莫搞科技7 小时前
鸿蒙跨端框架Flutter学习:CustomTween自定义Tween详解
学习·flutter·harmonyos
mocoding7 小时前
使用鸿蒙化flutter_fluttertoast替换Flutter原有的SnackBar提示弹窗
flutter·华为·harmonyos
2501_948120158 小时前
基于Flutter的跨平台社交APP开发
flutter
向哆哆9 小时前
构建健康档案管理系统:Flutter × OpenHarmony 跨端实现就医记录展示
flutter·开源·鸿蒙·openharmony·开源鸿蒙
2601_9498683610 小时前
Flutter for OpenHarmony 电子合同签署App实战 - 主入口实现
开发语言·javascript·flutter
向哆哆10 小时前
画栈 · 跨端画师接稿平台:基于 Flutter × OpenHarmony 的整体设计与数据结构解析
数据结构·flutter·开源·鸿蒙·openharmony·开源鸿蒙
2601_9498333911 小时前
flutter_for_openharmony口腔护理app实战+我的成就实现
flutter
2601_9496130212 小时前
flutter_for_openharmony家庭药箱管理app实战+用药知识详情实现
android·javascript·flutter
一起养小猫12 小时前
Flutter for OpenHarmony 实战 表单处理与验证完整指南
android·开发语言·前端·javascript·flutter·harmonyos