I'm trying to draw lines at a specific angle and the algorithm I'm using is :
x1,y1 - start coordinates of the line
x2 = x1 + l * cos(angle)
y2 = y1 + l * sin(angle)
My problem is that l, which is the length of the line is a fixed variable and if I want to add limits to the line end points. If I put the start points of the line in a rectangle is there a way to calculate the length of it, before I draw it so that it will not leave the rectangle's limits. Basicly I want to avoid that from happening.

For a line that goes up like they one in your example: Let $x_{ul}, y_{ul}$ be the upper left corner of the rectangle, and $x_{1}, y_{1}$ is the starting point of the line. Finally, let $\theta$ be your "angle".
The vertical distance of $x_{1}, y_{1}$ from the upper side of the rectangle is given by $a=|y_{1}-y_{ul}|$. At this point you should picture the right triangle forming using this vertical line, the upper side of the rectangle and the hypotenuse of length $l$. The angle between the hypotenuse and the vertical side is $\pi/2-\theta$. Finally, the length of hypotenuse $l$, is $$ l = a \cdot \frac{1}{cos(\frac{\pi}{2}-\theta)}. $$
Of course you would have to consider more cases since the line might intersect some other side and not upper one. But you can figure out this cases in a similar fashion.