# How can I find the intersection length of a circle and a rectangle?

I have the following information:

• The coordinates of the vertices of the rectangle.
• The radius and center position of the circle.

How can I find the length of the red line in the picture? (The rectangle isn't necessarily aligned with the X and Y axes, might be 'rotated').

Edit: if the circle is in diagonal to one of the corners of the rectangle, I still need the same thing. Like so:

• What is given? Do you have a ruler? – Hagen von Eitzen Jul 6 '14 at 16:10
• @barakmanos I added the known info to the question – Aviv Cohn Jul 6 '14 at 16:12
• do you need the answer for a general geometry? – Brian Jul 6 '14 at 16:14
• @B-Brock What does that mean? I need the answer for when I know the vertices of the rectangle and the radius and center of the circle. – Aviv Cohn Jul 6 '14 at 16:15
• like, what do you look for if the circle lies diagonally from one of the corners? – Brian Jul 6 '14 at 16:15

It looks like you want the length of the line segment overlap of a cross with arm length $r$ with a rectangle, where the edges of the rectangle and the arms of the cross are aligned.

First, rotate your reference frame so the rectangle is aligned with the axes (maybe not what you were looking for).

If your rectangle is defined by bottom left and top right corners $(x_1,y_1)$ and $(x_2,y_2)$, and your cross is defined by center $(x_0,y_0)$ and arm-length $r$, then you perform this algorithm:

if x0 < x1: // to the left
if y0 < y1: // bottom diagonal
overlap = 0
elif y0 < y2: // left center
overlap = max(r - (x1 - x0),0)
else: // top diagonal
overlap = 0
elif x0 < x2: // in center
if y0 < y1: // bottom
overlap = min(max(r - (y1 - y0),0), y2 -y1)
elif y0 < y2: // center
overlap_up = min(r, (y2 - y0))
overlap_down = min(r, (y0 - y1))
overlap_right = min(r, (x2 - x0))
overlap_left = min(r, (x0 - x1))
overlap_vertical = overlap_up + overlap_down
overlap_horizontal = overlap_left + overlap_right
overlap = overlap_vertical + overlap_horizontal
else: // top center
overlap = min(max(r - (y0 - y2),0), y2 -y1)
else: // to the right
if y0 < y1: // bottom diagonal
overlap = 0
elif y0 < y2: // right center
overlap = max(r - (x0 - x2), 0)
else: // top diagonal
overlap = 0

• Then why is the (x2,y2) relevant? It isn't in the formula. – Aviv Cohn Jul 6 '14 at 16:26
• Also, does this work if the rectangle isn't aligned with the two axes? – Aviv Cohn Jul 6 '14 at 16:34
• did this answer your question? did I treat the diagonal and center cases correctly? – Brian Jul 6 '14 at 18:09

You can find the equation of the line L1 which cuts the the circle using two point form. And then homogenize the equation of circle to find the intersection points and use those two points to form another line equation L2 using two point form and then find another line L3 parallel to L2 but which is a tangent to the circle. At last find the shortest distance between L2 and L3 using the formula d= |Ax1+By1+C/ √(A^2 +B^2)|