判断点是否在多边形区域内
最近在工作的时候,需要判断一个点,是否在一个数据区域内,参考了其他朋友提供方法,现在汇总了MFC、C#、java下的三种判断方式:
一、MFC
vc++6工具自带函数,引用及使用方法如下:
1、如下调用:
CRgn rgn;
rgn.CreatePolygonRgn(PointArray, 100, 1);
if( rgn.PtInRegion(mxPoint.wX, mxPoint.wY))
其中,PointArray表示点的区域范围,mxPoint定义的struct如下:
typedef struct tagMXPoint
{
WORD wX;
WORD wY;
}MXPOINT;
CRgn定义的单元文件如下图:
二、C
1、代码如下:
System.Drawing.Drawing2D.GraphicsPath myGraphicsPath=new System.Drawing.Drawing2D.GraphicsPath();
Region myRegion=new Region();
myGraphicsPath.Reset();
//添家多边形点
Point p1=new Point(x1,y1);
Point p2=new Point(x2,y2);
Point p3=new Point(x3,y3);
Point p4=new Point(x4,y4);
myGraphicsPath.AddPolygon(LoadPoint(p1,p2,p2,p4));
myRegion.MakeEmpty();
myRegion.Union(myGraphicsPath);
//返回判断点是否在多边形里
bool myPoint =myRegion.IsVisible(MousePoint);
2、要先在nuget中添加如下都dotnet包:
任选一个安装即可,
三、java
code java 1:
public boolean checkWithJdkGeneralPath(Point2D.Doublepoint, List<Point2D.Double> polygon) {
java.awt.geom.GeneralPathp = new java.awt.geom.GeneralPath();
Point2D.Double first =polygon.get(0);
p.moveTo(first.x, first.y);
for (Point2D.Double d :polygon) {
p.lineTo(d.x, d.y);
}
p.lineTo(first.x, first.y);
p.closePath();
return p.contains(point);
}
code java 2:
public booleancheckWithJdkPolygon(Point2D.Double point, List<Point2D.Double> polygon) {
java.awt.Polygon p = new Polygon();
//java.awt.geom.GeneralPath
final int TIMES = 1000;
for (Point2D.Double d :polygon) {
int x = (int) d.x * TIMES;
int y = (int) d.y * TIMES;
p.addPoint(x, y);
}
int x = (int) point.x *TIMES;
int y = (int) point.y * TIMES;
return p.contains(x,y);
}
java.awt.Polygon 好像只能处理整数坐标值,不能处理浮点数。
上面三种方式,前两种验证确认是没问题的,java是其他朋友提供的,在此记录下,方便自己及需要的朋友。
参考:java/c# 判断点是否在多边形区域内https://www.cnblogs.com/LonelyEnvoy/p/5850661.html