2011-04-27 32 views
3

如何獲取GeneralPath對象的頂點?這似乎應該是可能的,因爲路徑是由點(lineTo,curveTo等)構成的。獲取GeneralPath的有序頂點

我想創建一個double [] []點數據(一個x/y座標數組)。

回答

5

您可以從PathIterator獲得積分。

我不知道您的制約因素是什麼,但如果你的形狀總是隻有一個封閉子路徑和只有直邊(沒有曲線),那麼下面的工作:

static double[][] getPoints(Path2D path) { 
    List<double[]> pointList = new ArrayList<double[]>(); 
    double[] coords = new double[6]; 
    int numSubPaths = 0; 
    for (PathIterator pi = path.getPathIterator(null); 
     ! pi.isDone(); 
     pi.next()) { 
     switch (pi.currentSegment(coords)) { 
     case PathIterator.SEG_MOVETO: 
      pointList.add(Arrays.copyOf(coords, 2)); 
      ++ numSubPaths; 
      break; 
     case PathIterator.SEG_LINETO: 
      pointList.add(Arrays.copyOf(coords, 2)); 
      break; 
     case PathIterator.SEG_CLOSE: 
      if (numSubPaths > 1) { 
       throw new IllegalArgumentException("Path contains multiple subpaths"); 
      } 
      return pointList.toArray(new double[pointList.size()][]); 
     default: 
      throw new IllegalArgumentException("Path contains curves"); 
     } 
    } 
    throw new IllegalArgumentException("Unclosed path"); 
} 

如果你的路徑可能包含曲線,您可以使用the flattening version of getPathIterator()

+0

甜,非常感謝。 – CodeBunny 2011-04-28 14:11:47

0

我會懷疑它始終是可能的,如果在所有... JavaDoc的說:

「的GeneralPath類表示 直線構成 立方一 幾何路徑,二次曲線和( Bézier)曲線。「

所以如果是曲線,它包含的點不一定是曲線的一部分。