問題描述
我是使用迭代器的新手,想知道如何遍歷線段上的每個點(準確地說是 Line2D.Double)——我需要檢查線上的每個點是否滿足某些要求.
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.
另外,給定一個路徑對象(如 GeneralPath),你會如何做同樣的事情(遍歷形狀輪廓上的每個點)?
Also, given a path object (like GeneralPath), how would you do the same thing (iterate through each 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();
}
推薦答案
Java API 中似乎沒有任何東西可以讓 Bresenham 的算法對用戶可見.所以我寫了一個遍歷一行的類.
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.
你可以這樣使用它:
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]]"));
這篇關于遍歷java中一行/路徑上的每個點的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!