iterate through each point on a line/path in java
I'm new to using iterators and was wondering how one would iterate through each point on a line segment (Line2D.Double, to be precise) -- I need to check to see if each point on the line fulfills certain requirements.
Also, given a path object (like GeneralPath), how would you do the same thing (iterate through ea开发者_如何转开发ch point on the outline of the shape)?
Ideally I'd like something like this (with either a line or a path):
Line2D line = new Line2D.Double(p1,p2);
for (Point2D point : line)
{
point.callSomeMethod();
}
There seems to be nothing in the Java API that makes Bresenham's algorithm user-visible. So I wrote a class that iterates over a line.
You can use it like this:
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]]"));
This will be slow because it will generate a new object for each point. If you need a faster solution, you might want to look into implementing the loop yourself, using the Bresenham algorithm.
Although your question is missing a lot of relevant info (ie I'm guessing a lot about your classes), the cleanest loop code is the foreach
syntax:
GeneralPath path = ...;
for (Line2D.Double point : path.getPoints()) {
// do something
}
Note however that you can not modify the object being iterated over with this kind of loop.
Use FlatteningPathIterator passing your Shape's path iterator.
Check the type returned:
PathIterator.SEG_MOVETO
PathIterator.SEG_LINETO
PathIterator.SEG_QUADTO
PathIterator.SEG_CUBICTO
PathIterator.SEG_CLOSE
Code:
PathIterator pi = path.getPathIterator(null);
while (pi.isDone() == false) {
double[] coordinates = new double[6];
int type = pi.currentSegment(coordinates);
pi.next();
}
精彩评论