I\'m looking for a way to draw an infinite line (a line with no end, also known as a ray) through 2 points. I can draw a line between 2 points with Line2D, no problem here.
By multiplying the second point by 10, you're not maintaining the x to y ratio. You need to subtract the origin before multiplying.
g2.draw(new Line2D.Double(0, 61.632653061218946, 944*10, (217.25510204080692-61.632653061218946)*10+61.632653061218946));
should work.
In general, g2.draw(new Line2D.Double(x0,y0,(x1-x0)*k+x0,(y1-y0)*k+y0)
should work.
The math behind this is to consider the two points as vectors (a
& b
). Now, define a third and fourth vector: the difference vector (d
) and the infinite end point vector (c
). The difference vector is simply the difference between b
and a
; that is d = b-a
. To find an infinite end point, we simply need to add infinity times the difference vector to the starting point (a
). So, c = a + d*k
, where k
is the arbitrarily large constant. After replacing d
, we have c = a+(b-a)*k
.
Let's do the math for a second.
(0, 61.632653061218946)-(944, 217.25510204080692)
. Slope is rise/run
, therefore m = 0.16485428917329234533898305084746
.(0, 61.632653061218946)-(9440, 2172.5510204080692)
; m = 0.22361423382911549300847457627119
.The slopes are different, which is just another way of saying the angles are different.
What you need to do is extend the line. You cannot just multiply both coordinates of one of the points by 10. First determine either an x or a y beyond the bounds of your canvas, then solve for the other value.
How do you do this?
First, get the equation for the line. A line is defined by y=m*x+b
, where m
is the slope, and b
is the y-intercept.
rise/run
= y2 - y1 / x2 - x1
). We get 0.16485428917329234533898305084746
b
(y - m*x
), you get 61.632653061218946
. In your case you already have this value as the y-intercept is the y-coordinate when x=0
.y = 0.16485428917329234533898305084746 * x + 61.632653061218946
Now, pick a sufficiently large x, say 10000. Plug this value in and solve for y. You get 1710.1755447941423993898305084746
.
Finally, draw your line to this new point, (0, 61.632653061218946)-(10000,1710.1755447941423993898305084746)
Great, now let's generalize this.
(x1, y1)
and (x2, y2)
. We want to solve for (10000, y3)
.y3 = m*x3 + b
, or y3 = m * 10000 + b
.b = y - m * x
, so plugging this in and arbitrarily choosing point 1, y3 = m * 10000 + y1 - m * x1
.m
: y3 = m * (10000 + x1) - y1
.m = (y2 - y1) / (x2 - x1)
, so plugging this in: y3 = ((y2 - y1) / (x2 - x1)) * (10000 + x1) - y1
.If your line doesn't start at x = 0
, you will need to repeat this process for x = 0
, meaning you should plot a line (0, ((y2 - y1) / (x2 - x1)) * x1 - y1)-(10000,((y2 - y1) / (x2 - x1)) * (10000 + x1) - y1)
.
Note: If x2 - x1
is 0, you have an infinite slope. This is a vertical line, and you'll have to handle this case separately.