这个东西基本上每个做视觉项目的工程师都用到过,前几天看见群里有人在问,正好最近有空写了个demo,没有测试过,应该是没有问题的。旋转中心如何计算这个问题还搞不明白的,自己好好锻炼下二维平面想象能力。
实现代码
首先定义坐标与圆的结构体,方便使用。
public struct Cicular { public double X; public double Y; public double R; } public struct mPoint { public double X; public double Y; }
计算经过三点坐标的圆的方法
/// <summary> /// 求经过三点的圆 /// </summary> /// <param name="px1">坐标1</param> /// <param name="px2">坐标2</param> /// <param name="px3">坐标3</param> /// <param name="C">结果圆</param> public void CalculateCicular(mPoint px1, mPoint px2, mPoint px3, out Cicular C) { double x1, y1, x2, y2, x3, y3; double a, b, c, g, e, f; x1 = px1.X; y1 = px1.Y; x2 = px2.X; y2 = px2.Y; x3 = px3.X; y3 = px3.Y; e = 2 * (x2 - x1); f = 2 * (y2 - y1); g = x2 * x2 - x1 * x1 + y2 * y2 - y1 * y1; a = 2 * (x3 - x2); b = 2 * (y3 - y2); c = x3 * x3 - x2 * x2 + y3 * y3 - y2 * y2; C.X = (g * b - c * f) / (e * b - a * f); C.Y = (a * g - c * e) / (a * f - b * e); C.R = Math.Sqrt((C.X - x1) * (C.X - x1) + (C.Y - y1) * (C.Y - y1)); }
计算坐标p1以坐标p2为中心旋转A角度后坐标p3
/// <summary>/// 计算坐标1以坐标2为中心旋转后坐标/// </summary>/// <param name="p1">坐标1</param>/// <param name="ARotate">旋转角度</param>/// <param name="p2">坐标2</param>/// <param name="p3">旋转后坐标</param>/// <returns>运行状态</returns>public string RotateAngle(mPoint p1, double ARotate, mPoint p2, out mPoint p3){try{double Rad = 0;Rad = ARotate * Math.Acos(-1) / 180;p3.X = (p2.X - p1.X) * Math.Cos(Rad) - (p2.Y - p1.Y) * Math.Sin(Rad) + p1.X;p3.Y = (p2.Y - p1.Y) * Math.Cos(Rad) + (p2.X - p1.X) * Math.Sin(Rad) + p1.Y;return "OK";}catch (Exception ex){p3.X=999999;p3.Y = 999999;return ex.Message;}}
简单使用
计算经过三点的圆
private void button1_Click(object sender, EventArgs e) { Cicular C; mPoint p1; mPoint p2; mPoint p3; p1.X =(double) point1_x.Value; p1.Y = (double)point1_y.Value; p2.X = (double)point2_x.Value; p2.Y = (double)point2_y.Value; p3.X = (double)point3_x.Value; p3.Y = (double)point3_y.Value; CalculateCicular(p1, p2, p3,out C); X.Value =(decimal) C.X; Y.Value = (decimal)C.Y; R.Value = (decimal)C.R; Console.WriteLine(C.X+"///"+C.Y+"///"+C.R); }
坐标值自行赋值。
计算旋转后坐标
private void button2_Click(object sender, EventArgs e) { mPoint p1, p2, p3; p1.X = (double)X.Value; p1.Y = (double)Y.Value; p2.X = (double)p_x.Value; p2.Y = (double)p_y.Value; //顺时针角度为负数 RotateAngle(p1,(double)A.Value,p2,out p3); point_xz_x.Value = (decimal)p3.X; point_xz_y.Value = (decimal)p3.Y; Console.WriteLine(p3.X + ","+ p3.Y); }
实现方式较为简单,主要是三角函数的应用。C#涉及到结构体以及out关键字的使用,关于out与ref的区别后续再讲。
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/241253.html