Flutter Path.computeMetrics() 的使用注意点

一个Path转虚线的扩展

java 复制代码
extension DashedPathExtension on Path {
  /// 转换为虚线 Path(安全版)
  /// [solidLength]:实线段长度(像素)
  /// [gapLength]:空线段长度(像素)
  /// 返回:新的虚线 Path(原 Path 不变)
  Path toDashedPath({
    required double solidLength,
    required double gapLength,
  }) {
    // 前置参数校验
    assert(solidLength > 0, "实线段长度必须大于0");
    assert(gapLength >= 0, "空线段长度不能为负数");

    // 1. 安全获取 PathMetrics 并校验
    //final PathMetrics metrics = computeMetrics();
    // // 校验1:PathMetrics 为空 → 返回空 Path
    //if (metrics.isEmpty) return Path();

    // 2. 遍历 metrics(兼容多段路径),避免 first 直接报错
    final Path dashedPath = Path();
    for (final PathMetric metric in computeMetrics()) {
      final double totalLength = metric.length;
      // 校验2:单段路径长度为0 → 跳过
      if (totalLength <= 0) continue;

      // 3. 循环绘制实线段(始终从实线开始)
      double currentDistance = 0.0;
      while (currentDistance < totalLength) {
        final double solidEnd = currentDistance + solidLength;
        final double actualEnd = solidEnd > totalLength ? totalLength : solidEnd;

        // 提取实线段并添加到虚线 Path
        final Path segment = metric.extractPath(currentDistance, actualEnd);
        dashedPath.addPath(segment, Offset.zero);

        // 跳过空线段
        currentDistance = solidEnd + gapLength;
      }
    }

    return dashedPath;
  }
}

注意点是这个

js 复制代码
    // 1. 安全获取 PathMetrics 并校验
    // final PathMetrics metrics = computeMetrics();
    // // // 校验1:PathMetrics 为空 → 返回空 Path
    // if (metrics.isEmpty) return Path();

这里调用了 metrics.isEmpty()

js 复制代码
  bool get isEmpty => !iterator.moveNext();

也就是调用了迭代器的moveNext() 再次遍历metrics 就会从第二个元素开始。 如果迭代器本身只有一个元素,这个时候调用metrics.first 救护报错no element。

相关推荐
恋猫de小郭1 分钟前
Flutter 开发怎么做 Agent ?从工程实战详细给你解读下
android·前端·flutter
安卓修改大师11 分钟前
安卓修改大师实战:Activity生命周期全解析与Smali插桩教程
android
峥嵘life31 分钟前
Android GMS 开机向导横竖屏切换配置总结
android·学习
apihz38 分钟前
PING 接口 PLUS 全球版 —— 免费全球多节点 Ping 检测 API教程
android
阿pin42 分钟前
Android随笔-epoll机制
android·epoll
plainGeekDev1 小时前
Gradle 写法 → Kotlin DSL
android·java·kotlin
binbin_521 小时前
Flutter 调用鸿蒙原生组件:MethodChannel 与 PlatformView 的选择和落地
开发语言·深度学习·flutter·harmonyos
三少爷的鞋1 小时前
协程深度解析:明明只有 8 个异步任务,为何 App 线程数瞬间突破 一倍?
android
GitLqr11 小时前
Flutter 3.44 插件内置 Kotlin (KGP) 双向兼容适配指南
android·flutter·dart
随遇丿而安15 小时前
第11周:Activity 跳转与传值 + 跳转优化
android