Iterate over every point on a line / path in java

I am new to using iterators and wondered how it would be possible to iterate over each point on a line segment (if necessary, Line2D.Double) - I need to check whether each point on the line meets certain requirements.

Also, if a path object is given (for example, GeneralPath), how would you do the same (repeat every point on the outline of the figure)?

Ideally, I would like something like this (with a line or path):

Line2D line = new Line2D.Double(p1,p2);
for (Point2D point : line)
{
   point.callSomeMethod();
}
+3
source share
5 answers

Nothing is visible in the Java API, which makes the Bresenham algorithm visible to the user. So, I wrote a class that iterates over a string.

You can use it as follows:

List<Point2D> points = new ArrayList<Point2D>();
Line2D line = new Line2D.Double(0, 0, 8, 4);
Point2D current;

for (Iterator<Point2D> it = new LineIterator(line); it.hasNext();) {
    current = it.next();
    points.add(current);
}

assertThat(points.toString(), 
    is("[Point2D.Double[0.0, 0.0], Point2D.Double[1.0, 0.0], " +
        "Point2D.Double[2.0, 1.0], Point2D.Double[3.0, 1.0], " +
        "Point2D.Double[4.0, 2.0], Point2D.Double[5.0, 2.0], " +
        "Point2D.Double[6.0, 3.0], Point2D.Double[7.0, 3.0], " +
        "Point2D.Double[8.0, 4.0]]"));
+8

, . , , .

+1

, (.. ), - foreach:

GeneralPath path = ...;
for (Line2D.Double point : path.getPoints()) {
    // do something
}

, , , .

0

:

  • PathIterator.SEG_MOVETO
  • PathIterator.SEG_LINETO
  • PathIterator.SEG_QUADTO
  • PathIterator.SEG_CUBICTO
  • PathIterator.SEG_CLOSE

:

PathIterator pi = path.getPathIterator(null);

while (pi.isDone() == false) {
    double[] coordinates = new double[6];
    int type = pi.currentSegment(coordinates);
    pi.next();
}
0

Use FlatteningPathIterator, passing the form path iterator.

0
source

All Articles