get Circle Center - Java java.lang

Java examples for java.lang:Math Geometry Shape

Description

get Circle Center

Demo Code


//package com.java2s;

import java.awt.geom.Point2D;

import java.util.List;

public class Main {
    /**/*from  w  w  w .  j  a  v a  2 s  .c  o m*/
     * 
     * @param ptList
     * @return
     */
    public static Point2D.Double getCircleCenter(List<Point2D.Double> ptList) {
        if (ptList == null) {
            return null;
        }

        switch (ptList.size()) {
        case 3:
            return getCircleCenter(ptList.get(0), ptList.get(1),
                    ptList.get(2));
        case 2:
            return new Point2D.Double((ptList.get(0).getX() + ptList.get(1)
                    .getX()) / 2.0, (ptList.get(0).getY() + ptList.get(1)
                    .getY()) / 2.0);
        default:
            return null;
        }
    }

    /**
     * @return
     */
    public static Point2D.Double getCircleCenter(Point2D ptA, Point2D ptB,
            Point2D ptC) {
        if (ptA == null || ptB == null || ptC == null) {
            return null;
        }

        double ax = ptA.getX();
        double ay = ptA.getY();
        double bx = ptB.getX();
        double by = ptB.getY();
        double cx = ptC.getX();
        double cy = ptC.getY();

        double c1 = bx - ax;
        double c2 = by - ay;
        double c3 = cx - ax;
        double c4 = cy - ay;
        double c5 = c1 * (ax + bx) + c2 * (ay + by);
        double c6 = c3 * (ax + cx) + c4 * (ay + cy);

        double denom = 2 * (c1 * (cy - by) - c2 * (cx - bx));

        if (denom == 0.0) {
            return null; // a, b, c must be collinear
        }

        double px = (c4 * c5 - c2 * c6) / denom;
        double py = (c1 * c6 - c3 * c5) / denom;

        return new Point2D.Double(px, py);
    }
}

Related Tutorials