計算兩條直線的交點

JaedongXue發表於2020-11-03

最近工作中用到這個,去網上搜了一下,有些能用但是不完善,沒考慮與x,y軸平行的情況,稍微修改一下如下,做個記錄,方便後續查閱:

    /**
     * 計算兩條直角的交點
     */
    public static TPoint getCrossPoint(ModelLine line1,ModelLine line2){
        TPoint result = new TPoint();
        if (line1.pt1.getX() == line1.pt2.getX()) {
            float a2 = (line2.pt1.getY()-line2.pt2.getY())/(line2.pt1.getX()-line2.pt2.getX());
            float b2 = line2.pt1.getY()-a2*(line2.pt1.getX());
            result.setJd(line1.pt1.getX());
            result.setWd(a2*result.getJd()+b2);
        } else if (line2.pt1.getX() == line2.pt2.getX()) {
            float a1 = (line1.pt1.getY()-line1.pt2.getY())/(line1.pt1.getX()-line1.pt2.getX());
            float b1 = line1.pt1.getY()-a1*(line1.pt1.getX());
            result.setJd(line2.pt1.getX());
            result.setWd(a1*result.getJd()+b1);
        } else {
            float a1 = (line1.pt1.getY()-line1.pt2.getY())/(line1.pt1.getX()-line1.pt2.getX());
            float b1 = line1.pt1.getY()-a1*(line1.pt1.getX());

            float a2 = (line2.pt1.getY()-line2.pt2.getY())/(line2.pt1.getX()-line2.pt2.getX());
            float b2 = line2.pt1.getY()-a2*(line2.pt1.getX());

            result.setJd((b1-b2)/(a2-a1));
            result.setWd(a1*result.getJd()+b1);
        }
        return result;
    }

java的程式碼寫演算法有些累贅,看著有些麻煩,但是看懂結構其實也不麻煩,其實就是點斜式求解的方法。其他實體類就不給出了。

相關文章