[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Draw a circle through three points in C#


The perpendicular bisector of any chord on a circle passes through the circle's center. To find the center given three points, simply find the perpendicular bisectors of the first two and last two pairs of points, and see where the bisectors intersect. After you find the center, calculate the distance from the center to one of the points to get the circle's radius.

If the bisectors do not intersect, the three points are colinear so they do not define a circle.

The following code shows how the program finds the circle defined by three points.

// Find a circle through the three points. private void FindCircle(PointF a, PointF b, PointF c, out PointF center, out float radius) { // Get the perpendicular bisector of (x1, y1) and (x2, y2). float x1 = (b.X + a.X) / 2; float y1 = (b.Y + a.Y) / 2; float dy1 = b.X - a.X; float dx1 = -(b.Y - a.Y); // Get the perpendicular bisector of (x2, y2) and (x3, y3). float x2 = (c.X + b.X) / 2; float y2 = (c.Y + b.Y) / 2; float dy2 = c.X - b.X; float dx2 = -(c.Y - b.Y); // See where the lines intersect. bool lines_intersect, segments_intersect; PointF intersection, close1, close2; FindIntersection( new PointF(x1, y1), new PointF(x1 + dx1, y1 + dy1), new PointF(x2, y2), new PointF(x2 + dx2, y2 + dy2), out lines_intersect, out segments_intersect, out intersection, out close1, out close2); if (!lines_intersect) { MessageBox.Show("The points are colinear"); center = new PointF(0, 0); radius = 0; } else { center = intersection; float dx = center.X - a.X; float dy = center.Y - a.Y; radius = (float)Math.Sqrt(dx * dx + dy * dy); } }

This code gets calculates the point (x1, y1) halfway between the first two points. It then calculates the vector <dx1, dy1> pointing in the direction of the perpendicular bisector for those points. It repeats those steps to find the perpendicular bisector of the second and third points.

The program then uses the FindIntersection method described in the post Determine where two lines intersect in C# to see where the two bisectors intersect.

If the bisectors don't intersect, then the points are colinear so the three original points don't define a circle. In that case the method displays an error message. Otherwise it sets the circle's center and radius and returns.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.