我有一组X和Y点来构建一个形状,我需要知道一个物体是否在其中,或者它的计算是什么?
X和Y coords示例:
522.56055 2389.885
544.96 2386.3406
554.18616 2369.2385
535.21814 2351.396
497.5552 2355.8396
我对数学并不是很好:(所以我希望得到一些支持,以了解它是如何完成的。
我目前所拥有的例子,但似乎并不可靠:
private boolean isInsideShape(Zone verifyZone, Position object)
{
int corners = verifyZone.getCorners();
float[] xCoords = verifyZone.getxCoordinates();
float[] yCoords = verifyZone.getyCoordinates();
float x = object.getX();
float y = object.getY();
float z = object.getZ();
int i, j = corners - 1;
boolean inside = false;
for(i = 0; i < corners; i++)
{
if(yCoords[i] < y && yCoords[j] >= y || yCoords[j] < y && yCoords[i] >= y)
if(xCoords[i] + (y - yCoords[i]) / (yCoords[j] - yCoords[i]) * (xCoords[j] - xCoords[i]) < x)
inside = !inside;
j = i;
}
return inside;
}
答案 0 :(得分:36)
您可以从这开始:http://en.wikipedia.org/wiki/Point_in_polygon
您也可以查看JTS Topology Suite。 特别是使用this function。
编辑:以下是使用JTS的示例:
import java.util.ArrayList;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.impl.CoordinateArraySequence;
public class GeoTest {
public static void main(final String[] args) {
final GeometryFactory gf = new GeometryFactory();
final ArrayList<Coordinate> points = new ArrayList<Coordinate>();
points.add(new Coordinate(-10, -10));
points.add(new Coordinate(-10, 10));
points.add(new Coordinate(10, 10));
points.add(new Coordinate(10, -10));
points.add(new Coordinate(-10, -10));
final Polygon polygon = gf.createPolygon(new LinearRing(new CoordinateArraySequence(points
.toArray(new Coordinate[points.size()])), gf), null);
final Coordinate coord = new Coordinate(0, 0);
final Point point = gf.createPoint(coord);
System.out.println(point.within(polygon));
}
}
以下是使用AWT的示例(更简单并且是Java SE的一部分):
import java.awt.Polygon;
public class JavaTest {
public static void main(final String[] args) {
final Polygon polygon = new Polygon();
polygon.addPoint(-10, -10);
polygon.addPoint(-10, 10);
polygon.addPoint(10, 10);
polygon.addPoint(10, -10);
System.out.println(polygon.contains(0, 0));
}
}
答案 1 :(得分:1)
我总是那样做:
Pick a point you know to be outside the shape.
Make a line between that point and the point you're trying to find whether it's inside the shape or not.
Count the number of sides of the shape the line crosses.
If the count is odd, the point is inside the shape.
If the count is even, the point is outside the shape.