【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),
              ),
            )
相关推荐
bst@微胖子3 小时前
Flutter之路由和导航
flutter
亚洲小炫风4 小时前
flutter 中各种日志
前端·flutter·日志·log
louisgeek6 小时前
Flutter 动画之 Implicit 隐式动画
flutter
勤劳打代码7 小时前
游刃有余 —— Isolate 轻量化实战
flutter·github·dart
RichardLai8811 小时前
[Flutter 基础] - Flutter基础组件 - Text
android·flutter
Ya-Jun21 小时前
常用第三方库精讲:cached_network_image图片加载优化
android·flutter
WDeLiang1 天前
Flutter 环境搭建
flutter·ios·visual studio code
程一个大前端1 天前
【Flutter高效开发】GetX指南:一文学会状态管理、路由与依赖注入
flutter
DEVIL1 天前
Flutter中各类Controller的本质
android·flutter
ak啊1 天前
Flutter UI 组件应用一:布局、交互、动画与弹窗
flutter