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。

相关推荐
maaath1 小时前
【maaath】Flutter for OpenHarmony 手表配饰应用实战开发
flutter·华为·harmonyos
maaath2 小时前
【maaath】Flutter for OpenHarmony 跨平台计算器应用开发实践
flutter·华为·harmonyos
重生之我是Java开发战士3 小时前
【MySQL】事务 & 用户与权限管理
android·数据库·mysql
怣疯knight5 小时前
Windows不安装 Android Studio如何打包安卓软件
android·windows·android studio
ke_csdn5 小时前
从Java演变到Kotlin下的jet pack
android
wenzhangli75 小时前
在低代码设计中践行 Harness Engineering
android·低代码·rxjava
xingpanvip6 小时前
星盘接口开发文档:组合三限盘接口指南
android·开发语言·前端·python·php·lua
TechMix7 小时前
【fkw学习笔记】Android 13 AOSP 源码添加系统预置应用实战指南
android·笔记·学习
maaath7 小时前
【maaath】Flutter for OpenHarmony 闹钟时钟应用开发实战
flutter·华为·harmonyos
云起SAAS7 小时前
私域直播系统UniApp源码 多商户商城+直播带货 微信小程序+H5+安卓iOS
android·微信小程序·uni-app·私域直播系统