【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),
              ),
            )
相关推荐
消失的旧时光-19433 小时前
Flutter 插件通信架构设计:从 Channel 到 FFI 的完整边界
flutter·ffi
郑梓斌6 小时前
Luban 2 Flutter:一行代码在 Flutter 开发中实现图片压缩功能
flutter·ios
哈__7 小时前
Flutter 开发鸿蒙 PC 第一个应用:窗口创建 + 大屏布局
flutter·华为·harmonyos
AiFlutter7 小时前
蓝牙调试助手开发(03):概要设计
flutter·低代码平台·aiflutter·aiflutter低代码·flutter低代码开发·蓝牙调试·蓝牙调试助手
西西学代码8 小时前
Flutter---框架
前端·flutter
消失的旧时光-19438 小时前
Flutter 与原生通信机制全解析:MethodChannel / EventChannel / BasicMessageChannel,一篇讲透(工程级)
flutter·dart·channel
kirk_wang8 小时前
Flutter Widget核心概念深度解析
flutter·移动开发·跨平台·arkts·鸿蒙
傅里叶8 小时前
Flutter移动端获取相机内参
前端·flutter
RaidenLiu9 小时前
Offstage / Visibility:不可见真的就不消耗性能吗
前端·flutter·性能优化
火柴就是我9 小时前
学习一些常用的混合模式之BlendMode. SRC_OVER
android·flutter