Java- Intersection point of a Polygon and Line

前端 未结 5 1286
轮回少年
轮回少年 2020-12-01 14:51

Is there any function that will give me the intersection point of a Polygon and Line2D ?

I have a Polygon and a line segment that I know

5条回答
  •  日久生厌
    2020-12-01 15:42

    If you are not restricted to use the Polygon and Line2D Objects I would recommend to use JTS.

    • Create LinearRing geometry (your polygon).
    • Create LineString geometry.
    • Create intersection Point(s) using the intersection method.

    Simple code example:

    // create ring: P1(0,0) - P2(0,10) - P3(10,10) - P4(0,10)
    LinearRing lr = new GeometryFactory().createLinearRing(new Coordinate[]{new Coordinate(0,0), new Coordinate(0,10), new Coordinate(10,10), new Coordinate(10,0), new Coordinate(0,0)});
    // create line: P5(5, -1) - P6(5, 11) -> crossing the ring vertically in the middle
    LineString ls = new GeometryFactory().createLineString(new Coordinate[]{new Coordinate(5,-1), new Coordinate(5,11)});
    // calculate intersection points
    Geometry intersectionPoints = lr.intersection(ls);
    // simple output of points
    for(Coordinate c : intersectionPoints.getCoordinates()){
        System.out.println(c.toString());
    }
    

    Result is:

    (5.0, 0.0, NaN)
    (5.0, 10.0, NaN)
    

提交回复
热议问题