I'm doing some canvas painting, and for performance reasons I want to get the coordinate of where a straight line enters and/or exits the screen.
To put it more simply, I want to find out the coordinates A'
and B'
in the illustration below. A
and B
are the original start- and end coordinates. A'
and B'
are the coordinates where the straight line from A
to B
enters or exits the screen bounds.
This seems like something that would be a common scenario, but I can't really find a simple and efficient algorithm for it.
I'm using Flutter, but I guess this is a general problem with a similar solution no matter which language (A and B are points, the screen is a rect).
We are given the following parameters and equations:
(xA, yA)
and(xB, yB)
;xMin <= x; x <= xMax; yMin <= y; y <= yMax
;(y-yA)*(xB-xA) = (yB-yA)*(x-A)
.We can use them to solve for the intersection points:
(x,y)
ofA'
by settingy=yMax
and solving the line equation forx
;(x,y)
ofB'
by settingx=xMax
and solving the line equation fory
;(x,y)
ofB'
by settingy=yMin
and solving the line equation forx
.To find all intersection points with the bounding box in all possible case, you could solve the equations for all 4 possible types of intersections, then discard solutions which either: