closestPoint static method
Implementation
static Point closestPoint(PickerGeometry geometry, Point point) {
// In order to find the closest line we use the point's angle
final angle = Geometry.angleFromOrigin(point);
final numVertices = geometry.vertices.length;
var smallestRelativeAngle = math.pi * 2;
var index1 = 0;
for (int i = 0; i < numVertices; i += 1) {
final relativeAngle = Geometry.normalizeAngle(geometry.angles[i] - angle);
if (relativeAngle < smallestRelativeAngle) {
smallestRelativeAngle = relativeAngle;
index1 = i;
}
}
final index2 = (index1 - 1 + numVertices) % numVertices;
final closestLine = geometry.lines[index2];
// Provided point is within the polygon
if (Geometry.distanceFromOrigin(point) <
Geometry.lengthOfRayUntilIntersect(angle, closestLine)) {
return point;
}
final Line perpendicularLine = Geometry.perpendicularThroughPoint(
closestLine,
point,
);
final Point intersectionPoint = Geometry.intersectLineLine(
closestLine,
perpendicularLine,
);
final Point bound1 = geometry.vertices[index1];
final Point bound2 = geometry.vertices[index2];
final Point upperBound;
final Point lowerBound;
if (bound1.x > bound2.x) {
upperBound = bound1;
lowerBound = bound2;
} else {
upperBound = bound2;
lowerBound = bound1;
}
final Point borderPoint;
if (intersectionPoint.x > upperBound.x) {
borderPoint = upperBound;
} else if (intersectionPoint.x < lowerBound.x) {
borderPoint = lowerBound;
} else {
borderPoint = intersectionPoint;
}
return borderPoint;
}