在C#的System.Drawing中根据两点及夹角求圆心与半径
已知圆上两点及圆心角求圆心与半径(C#实现)
前提说明
首先明确:题目中的夹角α默认指圆心角(即两条半径OA、OB的夹角)。如果α是圆周角,则圆心角为2α,需对应调整公式。所有角度计算需先转换为弧度。
数学推导
- 计算两点距离:
设A(x₁,y₁)、B(x₂,y₂),两点间距离d:d = √[(x₂ - x₁)² + (y₂ - y₁)²] - 计算半径:
根据三角函数关系,半径r:
(若α为圆周角,公式改为r = d / (2 * sin(α/2))r = d / (2 * sinα)) - 确定圆心位置:
圆心位于AB的中垂线上,且到A、B的距离均为r。存在两个可能的圆心(分别在AB线段的两侧):- 先计算AB的中点M((x₁+x₂)/2, (y₁+y₂)/2)
- 计算AB的方向向量
(dx, dy) = (x₂-x₁, y₂-y₁),中垂线的方向向量为(-dy, dx)和(dy, -dx)(对应两侧) - 中垂线上从M出发,长度为
h = r * cos(α/2)的点即为圆心
C# 实现代码(基于System.Drawing)
using System; using System.Drawing; public class CircleCalculator { /// <summary> /// 已知圆上两点及圆心角,计算所有可能的圆心和半径 /// </summary> /// <param name="pointA">圆上点A</param> /// <param name="pointB">圆上点B</param> /// <param name="centralAngleDegrees">圆心角(度数)</param> /// <returns>包含两个可能解的数组,每个元素为(圆心, 半径)</returns> public static (PointF Center, float Radius)[] CalculateCircle(PointF pointA, PointF pointB, float centralAngleDegrees) { // 角度转弧度 double centralAngleRadians = centralAngleDegrees * Math.PI / 180.0; double halfAngle = centralAngleRadians / 2; // 计算AB两点距离 double dx = pointB.X - pointA.X; double dy = pointB.Y - pointA.Y; double distanceAB = Math.Sqrt(dx * dx + dy * dy); // 计算半径 double radius = distanceAB / (2 * Math.Sin(halfAngle)); // 计算AB中点 double midX = (pointA.X + pointB.X) / 2.0; double midY = (pointA.Y + pointB.Y) / 2.0; // 中垂线的单位方向向量(两个方向) double perpendicularLength = Math.Sqrt(radius * radius - (distanceAB / 2) * (distanceAB / 2)); double unitPerpX = -dy / distanceAB; double unitPerpY = dx / distanceAB; // 计算两个可能的圆心 PointF center1 = new PointF( (float)(midX + unitPerpX * perpendicularLength), (float)(midY + unitPerpY * perpendicularLength) ); PointF center2 = new PointF( (float)(midX - unitPerpX * perpendicularLength), (float)(midY - unitPerpY * perpendicularLength) ); return new[] { (center1, (float)radius), (center2, (float)radius) }; } // 示例调用 public static void Main() { PointF a = new PointF(10, 10); PointF b = new PointF(20, 20); float angle = 70; // 圆心角70度 var circles = CalculateCircle(a, b, angle); Console.WriteLine($"解1:圆心({circles[0].Center.X:F2}, {circles[0].Center.Y:F2}),半径{circles[0].Radius:F2}"); Console.WriteLine($"解2:圆心({circles[1].Center.X:F2}, {circles[1].Center.Y:F2}),半径{circles[1].Radius:F2}"); } }
注意事项
- 若α为0度或180度,需特殊处理:α=180度时AB为直径,圆心是AB中点;α=0度时两点重合,无法确定唯一圆。
- 代码中使用
PointF处理浮点数坐标,若需整数坐标可自行转换为Point。
内容的提问来源于stack exchange,提问作者NGUYEN HAI
相关产品推荐
相关产品推荐

