C# 编程实现非自相交多边形质心
計(jì)算公式公式:?http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon
多邊形的質(zhì)心:
一個(gè)非自相交的n個(gè)頂點(diǎn)的多邊形(x0,y0), (x1,y1), ..., (xn?1,yn?1) 的質(zhì)心 (Cx,?Cy):
A是多邊形的有向面積:
.
在這些公式中,頂點(diǎn)被假定為沿多邊形周長(zhǎng)編號(hào)。此外,頂點(diǎn)(xn,yn)與(x0,y0)是相同的,意味著 對(duì)最后一次循環(huán)的i + 1?會(huì)回到i = 0.注意,如果點(diǎn)按順時(shí)針?lè)较蜻M(jìn)行編號(hào),按上述方法計(jì)算,會(huì)出現(xiàn)一個(gè)無(wú)法預(yù)知的結(jié)果;但在這種情況下質(zhì)心坐標(biāo)也會(huì)是正確的。
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.
?
對(duì)于那些難以理解這些公式∑符號(hào),下面給出C#的實(shí)現(xiàn)代碼:
?
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; } }
?
轉(zhuǎn)載于:https://www.cnblogs.com/thunderpanda/p/6233250.html
總結(jié)
以上是生活随笔為你收集整理的C# 编程实现非自相交多边形质心的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: VDP文件级恢复需要在用VDP备份的机器
- 下一篇: [09]CSS 边框与背景 (上)