如何在android中找到两条折线之间的相交?

时间:2018-03-28 13:08:20

标签: android google-maps

如何在android中找到两条折线之间的相交?

我尝试了以下所有选项

  1. PolyUtil.isLocationOnPath();

  2. RectF rectPathBounds=new RectF();
    
    path.computeBounds(rectPathBounds,true);
    
    if(rectPathBounds.contains((int) event.getX(), (int) event.getY())){
    
    }
    
  3. 3。boolean res = path.op(path1, Path.Op.INTERSECT);

    请帮我解决这些问题。提前致谢

1 个答案:

答案 0 :(得分:1)

/**
     * See if two line segments intersect. This uses the
     * vector cross product approach described below:
     * http://stackoverflow.com/a/565282/786339
     *
     * @param {Object} p point object with x and y coordinates
     *  representing the start of the 1st line.
     * @param {Object} p2 point object with x and y coordinates
     *  representing the end of the 1st line.
     * @param {Object} q point object with x and y coordinates
     *  representing the start of the 2nd line.
     * @param {Object} q2 point object with x and y coordinates
     *  representing the end of the 2nd line.
     */
    boolean doLineSegmentsIntersect(Point p,Point p2,Point q,Point q2) {
        Point r = subtractPoints(p2, p);
        Point s = subtractPoints(q2, q);

        float uNumerator = crossProduct(subtractPoints(q, p), r);
        float denominator = crossProduct(r, s);

        if (denominator == 0) {
            // lines are paralell
            return false;
        }

        float u = uNumerator / denominator;
        float t = crossProduct(subtractPoints(q, p), s) / denominator;

        return res = (t >= 0) && (t <= 1) && (u > 0) && (u <= 1);

    }

    /**
     * Calculate the cross product of the two points.
     *
     * @param {Object} point1 point object with x and y coordinates
     * @param {Object} point2 point object with x and y coordinates
     *
     * @return the cross product result as a float
     */
    float crossProduct(Point point1, Point point2) {
        return point1.x * point2.y - point1.y * point2.x;
    }

    /**
     * Subtract the second point from the first.
     *
     * @param {Object} point1 point object with x and y coordinates
     * @param {Object} point2 point object with x and y coordinates
     *
     * @return the subtraction result as a point object
     */
    Point subtractPoints(Point point1,Point point2) {
        Point result = new Point();
        result.x = point1.x - point2.x;
        result.y = point1.y - point2.y;

        return result;
    }