2012-07-06 143 views
2

Java PathIterator是否以順時針或逆時針順序爲您提供多邊形的點?Java PathIterator順時針或逆時針?

+0

產生按照'PathIterator' API, '迭代器移動到沿着路徑轉發的下一段只要在那個方向上有更多的點,主要的遍歷方向。' – 2012-07-06 16:37:17

回答

4

它按點在多邊形中定義的順序「走」。考慮下面的代碼示例我剛颳起:

c:\files\j>java ShapeTest 
Walking clockwise 
Currently at: 2.0 5.0 
Currently at: 4.0 4.0 
Currently at: 4.0 1.0 
Currently at: 0.0 1.0 
Currently at: 0.0 3.0 
Walking counter-clockwise 
Currently at: 0.0 3.0 
Currently at: 0.0 1.0 
Currently at: 4.0 1.0 
Currently at: 4.0 4.0 
Currently at: 2.0 5.0 

import java.awt.Polygon; 
import java.awt.geom.PathIterator; 
class ShapeTest { 
    /** 
    * Use points to make a pentagon 
       . 2,5 
     0,3 . . 4,3 
     0,1 . . 4,1 

    */ 
    public static void main(String...args) { 
     // from the top clockwise 
     int[] xClock = new int[] { 2,4,4,0,0 }; 
     int[] yClock = new int[] { 5,4,1,1,3 }; 

     // the reverse order from the clockwise way 
     int[] xCounter = new int[] { 0,0,4,4,2 }; 
     int[] yCounter = new int[] { 3,1,1,4,5 }; 

     Polygon clock = new Polygon(xClock, yClock, 5); 
     Polygon counter = new Polygon(xCounter, yCounter, 5); 

     int index = 0; 

     System.out.println("Walking clockwise"); 
     PathIterator clockIter = clock.getPathIterator(null); 

     while(!clockIter.isDone() && index < clock.npoints) { 
      float[] coords = new float[6]; 
      clockIter.currentSegment(coords); 
      System.out.println("Currently at: " + coords[0] + " " + coords[1]); 
      clockIter.next(); 
      index++; 
     } 

     index = 0; 

     System.out.println("Walking counter-clockwise"); 
     PathIterator counterIter = counter.getPathIterator(null); 
     while(!counterIter.isDone() && index < counter.npoints) { 
      float[] coords = new float[6]; 
      counterIter.currentSegment(coords); 
      System.out.println("Currently at: " + coords[0] + " " + coords[1]); 
      counterIter.next(); 
      index++; 
     } 

    } 
} 
+0

爲了記錄,我不知道爲什麼那些'0.0 0.0'部分出現。如果有人知道並且可以編輯並發表評論,我會很感激...這僅僅是一個簡單的例子,所以我沒有太多投入,但是是的... – corsiKa 2012-07-06 16:59:04

+0

那麼,你知道什麼?一年半後,有人過來,「等等,這是不正確的......」並修復它!真棒。 – corsiKa 2014-01-31 03:44:34

+0

只是一個額外的說明。我測試過,看起來如果你從一個路徑創建一個Area並從中獲得PathIterator,那麼它總是CCW。 – clankill3r 2015-02-12 10:07:37

相關問題