Does a Java PathIterator give you the points of a Polygon in clockwise or counterclockwise order?
Asked
Active
Viewed 2,832 times
2
-
According to the `PathIterator` API, `Moves the iterator to the next segment of the path forwards along the primary direction of traversal as long as there are more points in that direction.` – namenamename Jul 06 '12 at 16:37
1 Answers
5
It "walks" in the order the points are defined in the polygon. Consider the following code sample I just whipped up:
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
is produced by
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++;
}
}
}

modest_Supreme
- 5
- 3

corsiKa
- 81,495
- 25
- 153
- 204
-
For the record, I have no idea why those `0.0 0.0` parts show up. If anyone knows and could edit and leave a comment, I'd appreciate it... this was just a simple example, so I didn't put much into it, but yeah... – corsiKa Jul 06 '12 at 16:59
-
Well, what do ya know... a year and a half later, someone comes along and goes "wait, that isn't right..." and fixes it! Awesome. – corsiKa Jan 31 '14 at 03:44
-
Just an extra note. I tested and it seems if you create an Area from a path and get the PathIterator from that then it will be always CCW. – clankill3r Feb 12 '15 at 10:07