drawDash method

void drawDash(
  1. UiPaint paint,
  2. Canvas uiCanvas
)

Draws a dashed line along the path.

This method manually calculates and draws the dashes and gaps, as Flutter's native dash support can be inconsistent.

Implementation

void drawDash(UiPaint paint, Canvas uiCanvas) {
  List<double> dasharray = paint.getStrokeDasharray()!;
  List<Offsets>? dashed = _dashedPaths[dasharray.hashCode];
  if (dashed != null) {
    for (var offsets in dashed) {
      uiCanvas.drawLine(offsets.start, offsets.end, paint.expose());
    }
    return;
  }
  dashed = [];
  _dashedPaths[dasharray.hashCode] = dashed;
  int dashIdx = 0;
  double dashLength = dasharray[dashIdx];
  Offset? startOffset;
  for (var offset in _points) {
    if (offset.start) {
      dashIdx = 0;
      dashLength = dasharray[dashIdx];
      startOffset = offset.offset;
      continue;
    }
    if (startOffset == null) {
      _log.warning("Startoffset is null for dash $dashed and points $_points");
      startOffset = offset.offset;
      continue;
    }
    DirectionVector directionVector = DirectionVector.get(startOffset, offset.offset);
    while (directionVector.length > 0) {
      if (dashIdx % 2 == 0) {
        // draw line
        double remainingLength = 0;

        /// Draw a small line.
        (directionVector, remainingLength) = _drawLine(paint, uiCanvas, directionVector, dashLength, dashed);
        if (remainingLength != 0) {
          // we should draw the remaining length at the next vector
          dashLength = remainingLength;
        } else {
          ++dashIdx;
          dashLength = dasharray[dashIdx];
        }
      } else {
        // skip space
        double remainingLength = 0;
        (directionVector, remainingLength) = directionVector.reduce(dashLength);
        if (remainingLength != 0) {
          // we should "draw" the remaining space at the next vector
          dashLength = remainingLength;
        } else {
          ++dashIdx;
          if (dashIdx == dasharray.length) dashIdx = 0;
          dashLength = dasharray[dashIdx];
        }
      }
    }
    startOffset = offset.offset;
  }
}