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。

相关推荐
等你等了那么久3 小时前
Flutter打包APK记录
flutter·dart
モンキー・D・小菜鸡儿4 小时前
Android 系统TTS(文字转语音)解析
android·tts
2501_915909064 小时前
iOS 反编译防护工具全景解析 从底层符号到资源层的多维安全体系
android·安全·ios·小程序·uni-app·iphone·webview
Swizard4 小时前
速度与激情:Android Python + CameraX 零拷贝实时推理指南
android·python·ai·移动开发
summerkissyou19874 小时前
Android13-Audio-AudioTrack-播放流程
android·音视频
里纽斯5 小时前
RK平台Watchdog硬件看门狗验证
android·linux·rk3588·watchdog·看门狗·rk平台·wtd
三七吃山漆5 小时前
攻防世界——comment
android·python·web安全·网络安全·ctf
小a彤5 小时前
Flutter 与 Dart 语言的核心特性与应用
flutter
用户413079810615 小时前
终于懂了-ARouter原理初探
android