简体   繁体   中英

How to get the boundary of a java Polygon

Lets say I have a grid of points, and i use some functions to 'mark' some of them and add them to a regular Java Polygon , like this:

在此处输入图片说明

How should I determinate what the outer boundary of the Polygon is? Preferably returning as few points as necessary, Like so:

在此处输入图片说明

I tried the Polygon methods like getBounds or getPathIterator but they won't work in my case, since those will use the inner points as well.

Additionally, the red lines between points should not go diagonally.

Your images illustrate the solution already: You can safely remove the middle of 3 consecutive points if these 3 points form a vertial or a horizontal line (that is all have identical x or identical y coordinates.

This could be coded as a loop (pseudocode, didn't test it in compiler):

Point previous = null;
int vCount = 0, hCount = 0;
Iterator<Point> i = ...
List<Point> removablePoints = new ArrayList<>();
while (i.hasNext()) {
    Point current = i.next();
    if (previous != null) {
        if (current.x == previous.x) {
            ++hCount;
        } else {
            hCount = 1;
        }
        if (current.y == previous.y) {
            ++vCount;   
        } else {
            vCount = 1;
        }
   }
   if (vCount > 2) {
       removablePoints.add(current);
        --vCount;
   } else if (hCount > 2) {
       removablePoints.add(current);
       --hCount;
   }
   previous = current;
}

Since its not possible to remove the previous point easily in the iterator loop, just collect those points in a list and remove them after the loop (not shown).

The principle is easy, just count how many consecutive horizontal/vertical points there are and as soon as you found more than two drop the middle one (adjusting the counters to reflect the removed point).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM