Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

java - Using PathIterator to return all line segments that constrain an Area?

In Java, how would one employ PathIterator to iterate through the line segments that constrain an Area? The Area is bound only by lines (but curve support wouldn't hurt).

The method should return a collection of all the line segments.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This works (in all situations, I believe), but it might require more thorough testing:

Area area; // The value is set elsewhere in the code    
ArrayList<double[]> areaPoints = new ArrayList<double[]>();
ArrayList<Line2D.Double> areaSegments = new ArrayList<Line2D.Double>();
double[] coords = new double[6];

for (PathIterator pi = area.getPathIterator(null); !pi.isDone(); pi.next()) {
    // The type will be SEG_LINETO, SEG_MOVETO, or SEG_CLOSE
    // Because the Area is composed of straight lines
    int type = pi.currentSegment(coords);
    // We record a double array of {segment type, x coord, y coord}
    double[] pathIteratorCoords = {type, coords[0], coords[1]};
    areaPoints.add(pathIteratorCoords);
}

double[] start = new double[3]; // To record where each polygon starts

for (int i = 0; i < areaPoints.size(); i++) {
    // If we're not on the last point, return a line from this point to the next
    double[] currentElement = areaPoints.get(i);

    // We need a default value in case we've reached the end of the ArrayList
    double[] nextElement = {-1, -1, -1};
    if (i < areaPoints.size() - 1) {
        nextElement = areaPoints.get(i + 1);
    }

    // Make the lines
    if (currentElement[0] == PathIterator.SEG_MOVETO) {
        start = currentElement; // Record where the polygon started to close it later
    } 

    if (nextElement[0] == PathIterator.SEG_LINETO) {
        areaSegments.add(
                new Line2D.Double(
                    currentElement[1], currentElement[2],
                    nextElement[1], nextElement[2]
                )
            );
    } else if (nextElement[0] == PathIterator.SEG_CLOSE) {
        areaSegments.add(
                new Line2D.Double(
                    currentElement[1], currentElement[2],
                    start[1], start[2]
                )
            );
    }
}

// areaSegments now contains all the line segments

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...