Java examples for 2D Graphics:Line
Given a line formed by points Point1 and Point2, returns the point at a given distance from the Point1 along the same line.
/*/*from ww w. j av a2 s . co m*/ * Copyright (c) 2001-2002 Regents of the University of California. * All rights reserved. * * This software was developed at the University of California, Irvine. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Irvine. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ //package com.java2s; import java.awt.Point; public class Main { /** * Given a line formed by points Point1 and Point2, returns * the point at a given distance from the Point1 along the * same line. */ public static Point calcPointOnLineAtDist(Point Point1, Point Point2, int Dist) { double A = Point2.getX() - Point1.getX(); double B = -(Point2.getY() - Point1.getY()); //negate for graphic coords if (A == 0) { return new Point(Point1.x, Point2.y + Dist); } double angle = Math.atan(B / A); double a = Dist * Math.cos(angle); double b = Dist * Math.sin(angle); if (A > 0) { return new Point((int) (Point1.x + a), (int) (Point1.y - b)); } else { return new Point((int) (Point1.x - a), (int) (Point1.y + b)); } } }