在Flutter中如何在CustomPainter中绘制虚线?

new9mtju  于 2022-12-27  发布在  Flutter
关注(0)|答案(1)|浏览(193)

Flutter中没有原生API可以画虚线,An existing snippet可以画水平虚线,但是我找不到一个代码片段可以画从一点到另一点的任意虚线,还有一个叫做dash_painter的库可以画虚线路径,但是我只对画简单的虚线感兴趣,特别是,我正在寻找一个类似于canvas.drawLine(Offset p1, Offset p2, Paint paint)的用于绘制虚线的代码片段。

alen0pnh

alen0pnh1#

下面是在CustomPainter中绘制从点p1到点p2的虚线的函数:

void drawDashedLine(
      {required Canvas canvas,
      required Offset p1,
      required Offset p2,
      required int dashWidth,
      required int dashSpace,
      required Paint paint}) {
  // Get normalized distance vector from p1 to p2
  var dx = p2.dx - p1.dx;
  var dy = p2.dy - p1.dy;
  final magnitude = sqrt(dx * dx + dy * dy);
  dx = dx / magnitude;
  dy = dy / magnitude;

  // Compute number of dash segments
  final steps = magnitude ~/ (dashWidth + dashSpace);

  var startX = p1.dx;
  var startY = p1.dy;

  for (int i = 0; i < steps; i++) {
    final endX = startX + dx * dashWidth;
    final endY = startY + dy * dashWidth;
    canvas.drawLine(Offset(startX, startY), Offset(endX, endY), paint);
    startX += dx * (dashWidth + dashSpace);
    startY += dy * (dashWidth + dashSpace);
  }
}

示例用法:从(0,0)到(100,100)绘制一条红色虚线,虚线宽度为6,间距为4。

drawDashedLine(
    canvas: canvas,
    start: Offset(0, 0),
    end: Offset(100, 100),
    dashWidth: 6,
    dashSpace: 4,
    paint: Paint()..color = Colors.red..strokeWidth = 1);
  • 编辑 *

这是一个使用一个Canvas绘制方法调用的版本:

void drawDashedLine({
  required Canvas canvas,
  required Offset p1,
  required Offset p2,
  required double dashWidth,
  required double dashSpace,
  required Paint paint,
}) {
  final points = <Offset>[];
  final distance = (p2 - p1).distance;
  dashWidth /= distance;
  dashSpace /= distance;
  double t = 0;
  while (t < 1) {
    points.add(Offset.lerp(p1, p2, t)!);
    t += dashWidth;
    points.add(Offset.lerp(p1, p2, t.clamp(0, 1))!);
    t += dashSpace;
  }
  canvas.drawPoints(ui.PointMode.lines, points, paint);
}

相关问题