Java examples for java.lang:Math Geometry Line
circle Line Intersection
/**/* ww w . ja v a 2s .c o m*/ * Copyright 1998-2007, CHISEL Group, University of Victoria, Victoria, BC, Canada. * All rights reserved. */ //package com.java2s; import java.awt.geom.Point2D; public class Main { /** * @param theta Angle of line from (0,0), in radians * @param r Radius of the circle. * @param h X coordinate of centre of circle * @param k Y coordinate of centre of circle * @param result An array of 2 Point2D objects. Returns the 0, 1, or 2 points of intersection. * result [0] is the first point of intersection, result[1] is the sectod point of intersection * Either may be null. */ public static void circleLineIntersection(double theta, double r, double h, double k, Point2D[] result) { if (result.length != 2) { (new Exception("result must have length 2!")).printStackTrace(); return; } /* equation of a line, y=m*x+b, since one point at 0,0 and m=dy/dx=tan(theta) this line becomes y=tan(theta)*x equation of a circle, (x-h)^2 + (y-k)^2 = r^2 where (h,k) is the center of the circle and r is its radius after a bit of algebra and the quadratic equation, solving for x gives ... x = (-b +/- sqrt(b^2 - 4*a*c))/2*a where a = 1 + tan(theta)^2, b = -2*h - 2*k*tan(theta), and c = h^2 + k^2 - r^2 *** Note: There is absolutely no consideration of extreme values or other checks * for computational errors in the following code (ex. when theta approaches PI/2, tan(theta) approaches infinity) * As of Aug 2003, this method is only used to find the intersection of arcs with the corners of rounded rectangles * so these extremes do not come into play. */ double tanTheta = Math.tan(theta); double a = 1.0 + Math.pow(tanTheta, 2); double b = -2.0 * h - 2.0 * k * tanTheta; double c = Math.pow(h, 2) + Math.pow(k, 2) - Math.pow(r, 2); try { double x1 = (-b + Math.sqrt(Math.pow(b, 2) - 4.0 * a * c)) / (2.0 * a); double y1 = x1 * tanTheta; result[0] = new Point2D.Double(x1, y1); } catch (RuntimeException e) { e.printStackTrace(); result[0] = null; } try { double x2 = (-b - Math.sqrt(Math.pow(b, 2) - 4.0 * a * c)) / (2.0 * a); double y2 = x2 * tanTheta; result[1] = new Point2D.Double(x2, y2); } catch (RuntimeException e1) { e1.printStackTrace(); result[1] = null; } } }