Getting the line coordinates passing through a point at an angle is the easy part. Finding the end points of the line to be contained within the display rectangle is slightly more involved.
A line through a point P=(xp,yp)
with angle θ satisfies the equation
(x-xp)*SIN(θ)-(y-yp)*COS(θ) = 0
In parametric form the above is
P(t) = ( xp+t*COS(θ), yp+t*SIN(θ) )
where t
is the distance along the line from point P.
So if you want a line to span the entire drawing bounds (range
variable in your code) you have to find which t
corresponds to the top, bottom, left and right bounds and draw between the middle two.
// example angle at 15° through xp=2.0, yp=1.0
RectangleF range = new RectangleF(-3.0,-3.0, 6.0, 6.0);
double xp=2.0, yp=1.0;
double θ = 15.0*(Math.PI/180);
// If angle is 0°, 90° etc, the following will fail
double[] t = new double[4];
t[0] = (range.Left-xp)/Math.Cos(θ);
t[1] = (range.Right-xp)/Math.Cos(θ);
t[2] = (range.Top-yp)/Math.Sin(θ);
t[3] = (range.Bottom-yp)/Math.Sin(θ);
Array.Sort(t);
// pick middle two points
var A = new MyPoint() { X = xp+t[1]*Math.Cos(θ), Y = yp+t[1]*Math.Sin(θ) };
var B = new MyPoint() { X = xp+t[2]*Math.Cos(θ), Y = yp+t[2]*Math.Sin(θ) };
g.DrawLine(pen, A.ToPoint(), B.ToPoint());