#include "math.h" //#include"gept2dar.h" #include"geline2d.h" //#include"acarray.h" #include"gepnt2d.h" #include"gelnsg2d.h"
//以下为计算凸多边形面积方法 double areaofchimb(AcGePoint2dArray&ptarr) { AcGePoint2d *p=&ptarr.at(0); int i; int n;//点的个数 n=ptarr.length(); AcGePoint2d startpoint=ptarr.first(); AcGePoint2d endpoint=ptarr.last();
//求顶点到其余点的对角线长 double*arry=new double[n-3];
for(i=0;i<n-3;i++) // arry=(ptarr.at(0)).distanceTo(ptarr.at(i+2)); arry=ptarr[0].distanceTo(ptarr[i+2]); //求面积 double area=0; int j=0; for(j=0;j<n-2;j++) { double a; a=startpoint.distanceTo(ptarr[j+1]); // a=ads_distance(ptarr[0],ptarr[j+1]); double b; b=(ptarr[j+1]).distanceTo(ptarr[j+2]); // b=ads_distance(ptarr[j+1],ptarr[j+2]); double d; if (j<n-3) d=arry[j]; else d=startpoint.distanceTo(endpoint); // d=ads_distance(ptarr[0],ptarr[n-1]); double c=(a+b+d)/2; double s=sqrt(c*(c-a)*(c-b)*(c-d)); area+=s; } return area; }
//计算多边形面积 !!需要修改,补凸的时候可能使临近两点变凹 double area(AcGePoint2dArray &ptarr) { bool PointInPolygon(AcGePoint2d& pt,AcGePoint2dArray &ptarr); double areaoftriangle(AcGePoint2d ,AcGePoint2d,AcGePoint2d ); int n;//点的个数 n=4; ptarr.at(0).set(10,10); ptarr.at(1).set(10,20); ptarr.at(2).set(20,20); ptarr.at(3).set(20,10);
double area=0; double s=0; int i; for(i=0;i<n;i++) {double s=0; AcGePoint2d*ppt=new AcGePoint2d(ptarr.at(i)); ptarr.removeAt(i); bool flag; flag=PointInPolygon(*ppt,ptarr); if(flag==true) ptarr.insertAt(i,*ppt); else {AcGeLine2d*line=new AcGeLine2d(ptarr.at((i-1+n-1)%(n-1)),ptarr.at((i+n-1)%(n-1))); AcGePoint2d newpoint=(*ppt).mirror(*line); ptarr.insertAt(i,newpoint); s=s-2*(areaoftriangle(ptarr.at((n+i-1)%n),ptarr.at(i),ptarr.at((n+i+1)%n))); } } area=areaofchimb(ptarr); area=area-s; return area;
}
//以下判断点是否在多边形中,在返回false ,不在返回true bool PointInPolygon(AcGePoint2d& pt,AcGePoint2dArray &ptarr) { int n = ptarr.length(); int i, count=0; double yup, xup, ydown, xdown; // double y0, x0; double t; for( i=0; i< n; i++ ) { if((pt.x ==(ptarr.at(i).x)&&(pt.y==ptarr.at(i).y) //!!检查括号匹配不?? || (pt.x==(ptarr.at((i+1)%n).x))&&(pt.y==(ptarr.at((i+1)%n).y)))) return true; xup=(ptarr.at(i)).x>(ptarr.at((i+1)%n).x)?(ptarr.at(i)).xptarr.at((i+1)%n).x); yup=(ptarr.at(i)).y>(ptarr.at((i+1)%n).y)?(ptarr.at(i)).yptarr.at((i+1)%n).y); xdown=(ptarr.at(i)).x<(ptarr.at((i+1)%n).x)?(ptarr.at(i)).xptarr.at((i+1)%n).x); ydown=yup=(ptarr.at(i)).y<(ptarr.at((i+1)%n).y)?(ptarr.at(i)).yptarr.at((i+1)%n).y); if(pt.y>yup) continue; if(pt.y<ydown) continue; if(pt.y==ydown) if(pt.y<yup&&pt.x<xdown) count++; else continue; if(pt.y<yup&&pt.y>ydown) double t=xdown+(pt.y-ydown)*(xup-xdown)/(yup-ydown); if(t>pt.x) count++; if(t=pt.x) return true; } if(count%2==0) return false; else return true; }
//计算三角形面积 double areaoftriangle(AcGePoint2d pt1,AcGePoint2d pt2,AcGePoint2d pt3) { double a,b,c,l,s; a=pt1.distanceTo(pt2); b=pt2.distanceTo(pt3); c=pt3.distanceTo(pt1); l=(a+b+c)/2; s=sqrt(l*(l-a)*(l-b)*(l-c)); return s; }
|