C# 编程实现非自相交多边形质心
計算公式公式:?http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon
多邊形的質心:
一個非自相交的n個頂點的多邊形(x0,y0), (x1,y1), ..., (xn?1,yn?1) 的質心 (Cx,?Cy):
A是多邊形的有向面積:
.
在這些公式中,頂點被假定為沿多邊形周長編號。此外,頂點(xn,yn)與(x0,y0)是相同的,意味著 對最后一次循環的i + 1?會回到i = 0.注意,如果點按順時針方向進行編號,按上述方法計算,會出現一個無法預知的結果;但在這種情況下質心坐標也會是正確的。
In these formulas, the vertices are assumed to be numbered in order of their occurrence along the polygon's perimeter. Furthermore, the vertex (?xn,?yn?) is assumed to be the same as (?x0,?y0?), meaning?i + 1?on the last case must loop around to?i = 0. Note that if the points are numbered in clockwise order the areaA, computed as above, will have a negative sign; but the centroid coordinates will be correct even in this case.
?
對于那些難以理解這些公式∑符號,下面給出C#的實現代碼:
?
class Program {static void Main(string[] args){List<Point> vertices = new List<Point>();vertices.Add(new Point() { X = 1, Y = 1 });vertices.Add(new Point() { X = 1, Y = 10 });vertices.Add(new Point() { X = 2, Y = 10 });vertices.Add(new Point() { X = 2, Y = 2 });vertices.Add(new Point() { X = 10, Y = 2 });vertices.Add(new Point() { X = 10, Y = 1 });vertices.Add(new Point() { X = 1, Y = 1 });Point centroid = Compute2DPolygonCentroid(vertices);}static Point Compute2DPolygonCentroid(List<Point> vertices){Point centroid = new Point() { X = 0.0, Y = 0.0 };double signedArea = 0.0;double x0 = 0.0; // Current vertex Xdouble y0 = 0.0; // Current vertex Ydouble x1 = 0.0; // Next vertex Xdouble y1 = 0.0; // Next vertex Ydouble a = 0.0; // Partial signed area// For all vertices except lastint i=0;for (i = 0; i < vertices.Count - 1; ++i){x0 = vertices[i].X;y0 = vertices[i].Y;x1 = vertices[i+1].X;y1 = vertices[i+1].Y;a = x0*y1 - x1*y0;signedArea += a;centroid.X += (x0 + x1)*a;centroid.Y += (y0 + y1)*a;}// Do last vertexx0 = vertices[i].X;y0 = vertices[i].Y;x1 = vertices[0].X;y1 = vertices[0].Y;a = x0*y1 - x1*y0;signedArea += a;centroid.X += (x0 + x1)*a;centroid.Y += (y0 + y1)*a;signedArea *= 0.5;centroid.X /= (6*signedArea);centroid.Y /= (6*signedArea);return centroid;} }public class Point {public double X { get; set; }public double Y { get; set; } }
?
轉載于:https://www.cnblogs.com/thunderpanda/p/6233250.html
總結
以上是生活随笔為你收集整理的C# 编程实现非自相交多边形质心的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VDP文件级恢复需要在用VDP备份的机器
- 下一篇: [09]CSS 边框与背景 (上)