|
|
Title | Find the points where a line intersects a circle in Visual Basic .NET |
Description | This example shows how to find the points where a line intersects a circle in Visual Basic .NET. |
Keywords | graphics, line, circle, intersection |
Categories | Graphics, Algorithms, VB.NET |
|
|
The FindLineCircleIntersections function calculates the points of intersection between a line and a circle. It takes as parameters a circle's center point and radius, and two points on the line. It uses ByRef parameters to return the coordinates of the points of intersection. The function returns the number of points of intersection (0, 1, or 2).
To fund the points of intersection, the code considers the line as generated by the equations:
X(t) = x1 + (x2 - x1) * t
Y(t) = y1 + (y2 - y1) * t
Where t ranges from 0 to 1 to draw the line segment.
The code plugs these equations into the equation for a circle:
(X - Cx)^2 + (Y - Cy)^2 = radius^2
It then solves for t by using the quadratic formula. The result is 0, 1, or 2 values for t. It plugs those values back into the equations for the line to get the points of intersection.
|
|
Private Function FindLineCircleIntersections(ByVal cx As _
Single, ByVal cy As Single, ByVal radius As Single, _
ByVal x1 As Single, ByVal y1 As Single, ByVal x2 As _
Single, ByVal y2 As Single, ByRef ix1 As Single, ByRef _
iy1 As Single, ByRef ix2 As Single, ByRef iy2 As _
Single) As Integer
Dim dx As Single
Dim dy As Single
Dim A As Single
Dim B As Single
Dim C As Single
Dim det As Single
Dim t As Single
dx = x2 - x1
dy = y2 - y1
A = dx * dx + dy * dy
B = 2 * (dx * (x1 - cx) + dy * (y1 - cy))
C = (x1 - cx) * (x1 - cx) + (y1 - cy) * (y1 - cy) - _
radius * radius
det = B * B - 4 * A * C
If (A <= 0.0000001) Or (det < 0) Then
' No real solutions.
Return 0
ElseIf det = 0 Then
' One solution.
t = -B / (2 * A)
ix1 = x1 + t * dx
iy1 = y1 + t * dy
Return 1
Else
' Two solutions.
t = (-B + Sqrt(det)) / (2 * A)
ix1 = x1 + t * dx
iy1 = y1 + t * dy
t = (-B - Sqrt(det)) / (2 * A)
ix2 = x1 + t * dx
iy2 = y1 + t * dy
Return 2
End If
End Function
|
|
If you need to know, a point of intersection lies on the line segment if 0 <= t <= 1 and on an extension of the segment otherwise.
|
|
|
|
|
|