0

我已经测试了几种方法来检测路径中的两条线是否相互交叉,但它们都不适合我。我在下面显示的最后一个代码也不起作用,因为它正在检测交叉点(一条线与另一条线重叠),尽管我正在绘制一个没有重叠线的形状。很难说可能出了什么问题,因为我数学不好,我不知道我的计算是否正确。我真的很感谢可以改进代码的计算或想法的一些帮助。谢谢!

代码中循环的部分抛出数组列表中的点:

// Intersection control
    if(touchActionUp) {
        //startDrawLine = false;

        // Loop throw all points except the last 3
        for (int i = 0; i < points.size()-3; i++) {
            Line line1 = new Line(points.get(i), points.get(i+1));

            // Begin after the line above and check all points after that
            for (int j = i + 2; j < points.size()-1; j++) {
                Line line2 = new Line(points.get(j), points.get(j+1));

                // Call method to check intersection
                if(checkIntersection(line1, line2)) {
                    Log.i("Interception: ", "YES!");
                }
            }
        }
    }

检查交叉点的方法:

// Method to check for intersection between lines
private boolean checkIntersection(Line line1, Line line2) {

    int x1 = line1.pointX1;
    int x2 = line1.pointX2;
    int x3 = line2.pointX1;
    int x4 = line2.pointX2;

    int y1 = line1.pointY1;
    int y2 = line1.pointY2;
    int y3 = line2.pointY1;
    int y4 = line2.pointY2;

    float x1m = (x1 + x2) / 2;
    float y1m = (y1 + y2) / 2;
    float x2m = (x3 + x4) / 2;
    float y2m = (y3 + y4) / 2;

    float a1 = (y2 - y1);
    float b1 = (x2 - x1);
    float a2 = (y4 - y3);
    float b2 = (x4 - x3);

    float c1 = a1 * (x3 - x1m) + b1 * (y3 - y1m);
    float c2 = a1 * (x4 - x1m) + b1 * (y4 - y1m);
    float c3 = a2 * (x1 - x2m) + b2 * (y1 - y2m);
    float c4 = a2 * (x2 - x2m) + b2 * (y2 - y2m);

    if(Math.signum(c1) != Math.signum(c2) && Math.signum(c3) != Math.signum(c4)) {
        return true;
    }

    return false;
}
4

0 回答 0