2014-03-24 47 views
0

我剛開始學習計算機圖形學,也是JAVA新手。這是我的java applet,它執行掃描線算法,它在某些情況下效果很好。任何人都可以幫助我知道我究竟在哪裏錯了嗎?Java掃描線多邊形填充算法

您可以在這裏查看整個代碼= http://codeshare.io/9uVUf 在此先感謝。

+0

'它適用於某些情況'告訴我們何時何地不能按照您的預期工作。 – PeterMmm

+0

1)爲什麼要編寫一個小程序?如果這是由於規格。由老師,請參考[爲什麼CS老師應該停止教Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/)。 2)爲了更快地獲得更好的幫助,請發佈[MCVE](http://stackoverflow.com/help/mcve)(最小完整和可驗證示例)。 3)試着描述a)你預期會發生什麼b)實際發生了什麼,以及對於效用c)爲什麼你期望(a)發生。 –

+0

我發現它只有在順時針方向給出座標時才起作用。那麼我是否需要按順時針方向排列邊緣?如果是的話? – user3450334

回答

0

我在C++和OpenGL中做了類似的東西。使用凹面和凸面,不知道是否與所有多邊形。

我不知道這是否是最好的解決方案,但它適用於我。

bool GraphicObject::IsMouseInside(int x, int y) 
{ 
    if (Points.size() < 2) 
    { 
     return false; 
    } 

    int count = 0; 
    float ti; 
    float yint = y; 
    float xint = 0; 

    for (size_t i = 0; i < Points.size() - 1; i++) 
    { 
     auto p1 = Points[i + 1]; 
     auto p2 = Points[i]; 

     if (p1.x == x && p1.y == y) 
     { 
      return true; 
     } 

     ti = 0; 

     if ((p2.y - p1.y) != 0) 
     { 
      ti = (yint - p1.y)/(p2.y - p1.y); 
     } 

     if (ti > 0 && ti < 1) 
     { 
      xint = p1.x + (p2.x - p1.x) * ti; 

      // HACK: To point (line) are impossible to select. 
      // Add an error margin. 
      if (Points.size() == 2) 
      { 
       // TODO: Use euclidean distance for this. Is better? 
       if ((xint + 8) > x || (xint - 8) > x) 
       { 
        count++; 
       } 
      } 
      else 
      { 
       if (xint > x) 
       { 
        count++; 
       } 
      } 
     } 
    } 

    // last point with first. 
    auto p1 = Points[Points.size() - 1]; 
    auto p2 = Points[0]; 

    ti = (yint - p1.y)/(p2.y - p1.y); 

    if (ti > 0 && ti < 1) 
    { 
     xint = p1.x + (p2.x - p1.x) * ti; 

     if (xint > x) 
     { 
      count++; 
     } 
    } 

    return count % 2 != 0; 
}