【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),
              ),
            )
相关推荐
阅文作家助手开发团队_山神9 小时前
第三章: Flutter-quill 数据格式Delta
flutter
阅文作家助手开发团队_山神9 小时前
第二章:Document 模块与 DOM 树详解
flutter
程序员老刘9 小时前
20%的选择决定80%的成败
flutter·架构·客户端
肥肥呀呀呀18 小时前
flutter 中Stack 使用clipBehavior: Clip.none, 超出的部分无法响应所有事件
flutter
SY.ZHOU18 小时前
Flutter如何支持原生View
flutter
sg_knight18 小时前
Flutter嵌入式开发实战 ——从树莓派到智能家居控制面板,打造工业级交互终端
android·前端·flutter·ios·智能家居·跨平台
张风捷特烈20 小时前
每日一题 Flutter#4 | 说说组件 build 函数的作用
android·flutter·面试
小镇梦想家2 天前
鸿蒙NEXT-Flutter(2)
flutter
至善迎风2 天前
一键更新依赖全指南:Flutter、Node.js、Kotlin、Java、Go、Python 等主流语言全覆盖
java·flutter·node.js
椒盐煎蛋2 天前
新建的Flutter插件工程,无法索引andorid工程代码;无法索引io.flutter包下代码。
flutter