java/c# 判斷點是否在多邊形地區內

來源:互聯網
上載者:User

最近幫別人解決了一個問題,如何判斷一個座標點,是否在多邊形地區內(二維)。

在網上搜尋了一圈,都是自己寫代碼,有多種演算法,分凸多邊形、凹多邊形,總之是麻煩。

 

繼續搜尋,瞭解到 Java/dotnet 內建的類庫中,都有現成的類函數,可以解決這個問題。

考慮到瞭解的人不多,特將相關知識共用出來,也許大家以後也用得著。

 

a) dotnet 中,用 System.Drawing.Drawing2D.GraphicsPath 和 Region 類聯合起來,然後用 Region.IsVisible(point) 函數,可以判斷點是否在多邊形地區內。

 

b) Java 中,使用 java.awt.Polygon.contains(point) ,或者 java.awt.geom.GeneralPath.contains(point) 函數,都可以判斷點是否在多邊形地區內。

 

以下是程式碼範例:

code c#:

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);

 

code java 1:

public boolean checkWithJdkGeneralPath(Point2D.Double point, List<Point2D.Double> polygon) {
  java.awt.geom.GeneralPath p = 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 boolean checkWithJdkPolygon(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 好像只能處理整數座標值,不能處理浮點數。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.