Skip to content

Instantly share code, notes, and snippets.

@maiconhellmann
Last active July 15, 2022 07:22
Show Gist options
  • Save maiconhellmann/24c5a2ebf53063cf4ddb4498e70487c2 to your computer and use it in GitHub Desktop.
Save maiconhellmann/24c5a2ebf53063cf4ddb4498e70487c2 to your computer and use it in GitHub Desktop.
/**
* Check if a point cliked is in the are of a line.
*/
class CheckLineClicked {
/**
* Returns the distance between a point(clickPosition) and a line(start and end point).
*/
fun checkLineClicked(clickPosition: PointF, startPoint: PointF, endPointF: PointF): Float {
val x = clickPosition.x
val y = clickPosition.y
val x1 = startPoint.x
val y1 = startPoint.y
val x2 = endPointF.x
val y2 = endPointF.y
return checkLineClicked(x, y, x1, y1, x2, y2)
}
private fun checkLineClicked(x: Float, y: Float, x1: Float, y1: Float, x2: Float, y2: Float): Float {
val a = x - x1
val b = y - y1
val c = x2 - x1
val d = y2 - y1
val dot = a * c + b * d;
val lenSq = c * c + d * d;
var param = -1f
if (lenSq != 0f) //in case of 0 length line
param = dot / lenSq
val yy: Float
val xx: Float
if (param < 0) {
xx = x1
yy = y1
} else if (param > 1) {
xx = x2
yy = y2
} else {
xx = x1 + param * c
yy = y1 + param * d
}
val dx = x - xx
val dy = y - yy
return sqrt(dx * dx + dy * dy)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment