get Median Line - Java java.lang

Java examples for java.lang:Math Geometry Line

Description

get Median Line

Demo Code


//package com.java2s;

import java.awt.geom.Line2D;

import java.awt.geom.Point2D;

public class Main {
    /**/*from w ww.jav a  2  s. com*/
     * @return median line or null if any argument is invalid
     */
    public static Line2D.Double getMedianLine(Line2D line1, Line2D line2) {
        if (line1 == null || line2 == null) {
            return null;
        }

        Point2D ptA = line1.getP1(), ptB = line1.getP2();
        Point2D ptC = line2.getP1(), ptD = line2.getP2();

        Line2D line3 = new Line2D.Double(ptA, ptC);
        Line2D line4 = new Line2D.Double(ptB, ptD);

        Point2D ptM, ptN;

        if (line3.intersectsLine(line4)) {
            ptM = new Point2D.Double((ptA.getX() + ptD.getX()) / 2,
                    (ptA.getY() + ptD.getY()) / 2);
            ptN = new Point2D.Double((ptB.getX() + ptC.getX()) / 2,
                    (ptB.getY() + ptC.getY()) / 2);
        } else {
            ptM = new Point2D.Double((ptA.getX() + ptC.getX()) / 2,
                    (ptA.getY() + ptC.getY()) / 2);
            ptN = new Point2D.Double((ptB.getX() + ptD.getX()) / 2,
                    (ptB.getY() + ptD.getY()) / 2);
        }

        return new Line2D.Double(ptM, ptN);
    }

    /**
     * @return median line or null if any argument is invalid
     */

    public static Line2D.Double getMedianLine(Point2D ptA, Point2D ptB,
            Point2D ptC, Point2D ptD) {
        if (ptA == null || ptB == null || ptC == null || ptD == null) {
            return null;
        }
        return getMedianLine(new Line2D.Double(ptA, ptB),
                new Line2D.Double(ptC, ptD));
    }
}

Related Tutorials