How can I split a Polygon by a Line?

后端 未结 5 1250
小蘑菇
小蘑菇 2020-12-05 01:03

As shown below,

Is it possible to split a Polygon by a Line? (into two Polygons). If the line doesn\'t go all th

5条回答
  •  鱼传尺愫
    2020-12-05 01:25

    It's possible, but if the polygon is not convex then splitting it across a line potentially leads to more than two polygons.

    Traverse the polygons edges, and for each edge determine whether it intersects the line. Find the first such edge which does so. Continue traversing until you find another such edge, but add each you encounter along the way to a new polygon (including the part of the first edge which was split by the line which is on "this side" and likewise for the last edge). Finally, add a closing edge to the new Polygon. Now continue processing edges - on the other side of the line, creating another Polygon in the same manner. You now have two polygons split across the line. The same technique will work, if you are careful, with splitting a non-convex polygon into multiples polygons.

    Beware of corner cases such as the line crossing a vertex of the polygon, and the line not intersecting the polygon at all.

    Edit: As xan points out, this won't handle all non-convex cases properly. This can be fixed with a small modification to the algorithm. Before you add the closing edge as described above, you must first check if any further edge of the original polygon would intersect that closing edge; if so, you close only up to that edge and continue processing further edges from that point.

提交回复
热议问题