Find the tangent lines between a point and a circle in C#

This isn't too hard if you're familiar with the example Determine where two circles intersect in C#.

Consider the figure on the right. R is the radius of the circle. You can easily calculate the distance D between the external point and the circle's radius by using the Pythagorean theorem. If the point P is (Px, Py) and the circle's center C is (Cx, Cy), then .

The tangent meets the circle's radius at a 90 degree angle so you can use the Pythagorean theorem again to find .

Believe it or not, you're now done because the tangent points P0 and P1 are the the points of intersection between the original circle and the circle with center P and radius L. Simply use the code from the example Determine where two circles intersect in C# to find those points.

The following code shows how the FindTangents method used by the example program finds the tangent points.

// Find the tangent points for this circle and external point.
// Return true if we find the tangents, false if the point is
// inside the circle.
private bool FindTangents(PointF center, float radius,
PointF external_point, out PointF pt1, out PointF pt2)
{
// Find the distance squared from the
// external point to the circle's center.
double dx = center.X - external_point.X;
double dy = center.Y - external_point.Y;
double D_squared = dx * dx + dy * dy;
if (D_squared < radius * radius)
{
pt1 = new PointF(-1, -1);
pt2 = new PointF(-1, -1);
return false;
}

// Find the distance from the external point
// to the tangent points.
double L = Math.Sqrt(D_squared - radius * radius);

// Find the points of intersection between
// the original circle and the circle with
// center external_point and radius dist.
FindCircleCircleIntersections(
center.X, center.Y, radius,
external_point.X, external_point.Y, (float)L,
out pt1, out pt2);

return true;
}

The code calculates the distance D squared. It uses that to calculate L and then calls FindCircleCircleIntersections to find the intersections between the two circles.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.