воскресенье, 5 января 2014 г.

How to know if point is inside polygon


The lines of polygon can be imagined like straights. The point can be inside, outside or on the polygon. The most simplest way find intersections of the line from point with lines of the polygons. We will draw line from point to 0,0. So if it will be on the polygon lines or outside it will intersects polygon more than 1 time, in the other case it will intersects only one time. The first step in cycle find all intersections with line from point with polygon. It can be done with method from Slope of a Straight Line Android.


Then we count if required point is on the polygon lines:

public boolean isOnSegment(float[] coor) {
// (x-x1)/(x2-x1)=(y-y1)/(y2-y1)
boolean status = false;
if (coor[0] != 0 && coor[1] != 0) {

if (round(((coor[0] - mX1) / (mX2 - mX1)), 2) == round((coor[1] - mY1) / (mY2 - mY1), 2)) {
status = true;
}
// if horizontal line
if (mY1 == mY2 && mY1 == coor[1]) {
if (mX1 < mX2 && coor[0] > mX1 && coor[0] < mX2) {
status = true;
}
if (mX1 > mX2 && coor[0] < mX1 && coor[0] > mX2) {
status = true;
}
}
// if vertical line
if (mX1 == mX2 && mX1 == coor[0]) {
if (mY1 < mY2 && coor[1] > mY1 && coor[1] < mY2) {
status = true;
}
if (mY1 > mY2 && coor[1] < mY1 && coor[1] > mY2) {
status = true;
}
}
}
if (!checkSumVectors(coor)) status = false;
return status;
}


public static float round(float number, int scale) {
int pow = 10;
for (int i = 1; i < scale; i++)
pow *= 10;
float tmp = number * pow;
return (float) (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) / pow;

}

Комментариев нет:

Отправить комментарий