Search code examples
javaaffinetransformpath-iterator

PathIterator for java.awt.Rectangle always gives (0,0)


In my code, I create an instance of java.awt.Rectangle with a corner and length and width. Then I apply a rotation affine transformation(at) on it to rotate it by a certain angle.

Then I fetch rectangle's PathIterator and iterate the geometry as:

PathIterator i = rectangle.getPathIterator(at);
while (!i.isDone()) {
    double[] xy = new double[2];
    i.currentSegment(xy);
}

While I expect 4 points(or 5 as first and last may be same), what I get is 6 points. And more surprising is that last point is always (0,0). (0,0) is not part of rectangle geometry, but I still get it always. What is the reason behind this behaviour?


Solution

  • Check the return value of currentSegment. The last "point" will be of type PathIterator.SEG_CLOSE, which is documented as:

    The segment type constant that specifies that the preceding subpath should be closed by appending a line segment back to the point corresponding to the most recent SEG_MOVETO.

    The point data associated with this type is implicit (i.e. the first and last points in the path). Nothing is written to the array when currentSegment returns SEG_MOVETO; the point (0, 0) you're seeing on the last call is the value that the array was initialised with when you created it.