isPointOnPath function
Checks if the given point lies on the specified path.
Returns true if the point is on the path, otherwise returns false.
Implementation
bool isPointOnPath(Offset point, Path path, double pathWidth) {
// Early exit: check if point is within the path's bounding box (expanded by stroke width)
final bounds = path.getBounds();
final strokeWidth = pathWidth.clamp(4, 100);
if (point.dx < bounds.left - strokeWidth ||
point.dx > bounds.right + strokeWidth ||
point.dy < bounds.top - strokeWidth ||
point.dy > bounds.bottom + strokeWidth) {
return false;
}
PathMetric? pathMetric = path.computeMetrics().firstOrNull;
if (pathMetric == null) return false;
double totalLength = pathMetric.length;
// Use distance squared for faster comparison (avoid sqrt)
final strokeWidthSquared = strokeWidth * strokeWidth;
// Use larger step for better performance
final step = totalLength > 100 ? totalLength / 50 : 2.0;
for (double d = 0.0; d <= totalLength; d += step) {
Tangent? tangent = pathMetric.getTangentForOffset(d);
if (tangent == null) continue;
// Check if the point is within stroke the width of the path
// Using distance squared instead of distance for performance
final dx = tangent.position.dx - point.dx;
final dy = tangent.position.dy - point.dy;
if (dx * dx + dy * dy <= strokeWidthSquared) {
return true;
}
}
return false;
}