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。

相关推荐
阿明的小蝴蝶20 小时前
记一次Gradle环境的编译问题与解决
android·前端·gradle
汪海游龙21 小时前
开源项目 Trending AI 招募 Google Play 内测人员(12 名)
android·github
qq_283720051 天前
MySQL技巧(四): EXPLAIN 关键参数详细解释
android·adb
没有了遇见1 天前
Android 架构之网络框架多域名配置<三>
android
小白学鸿蒙1 天前
使用Flutter从0到1构建OpenHarmony/HarmonyOS应用
flutter·华为·harmonyos
myloveasuka1 天前
[Java]单列集合
android·java·开发语言
fundroid1 天前
Room 3.0 完全解析:一次面向未来的现代化重构
android·数据库·database·kmp
漂洋过海来看你啊1 天前
Jetpack Compose高效列表实战:状态管理与性能优化指南
android
张宏2361 天前
android camera hal3-camera_module_t
android
hongtianzai1 天前
Laravel9.X核心特性全解析
android·java·数据库