Here are my assumptions:
- the bottom-left corner of your image is the origin (the point with coordinates
(0, 0)
)
- you have an image with width
w
and height h
- you can put the vector in the form of a linear equation (i.e.,
y=mx+b
, where m
is the slope and b
is the y-intercept)
Given those assumptions, do the following to find the discrete coordinates where the line intersects the edges of your image:
/// <summary>
/// Find discreet coordinates where the line y=mx+b intersects the edges of a w-by-h image.
/// </summary>
/// <param name="m">slope of the line</param>
/// <param name="b">y-intercept of the line</param>
/// <param name="w">width of the image</param>
/// <param name="h">height of the image</param>
/// <returns>the points of intersection</returns>
List<Point> GetIntersectionsForImage(double m, double b, double w, double h)
{
var intersections = new List<Point>();
// Check for intersection with left side (y-axis).
if (b >= 0 && b <= h)
{
intersections.Add(new Point(0.0, b));
}
// Check for intersection with right side (x=w).
var yValRightSide = m * w + b;
if (yValRightSide >= 0 && yValRightSide <= h)
{
intersections.Add(new Point(w, yValRightSide));
}
// If the slope is zero, intersections with top or bottom will be taken care of above.
if (m != 0.0)
{
// Check for intersection with top (y=h).
var xValTop = (h - b) / m;
if (xValTop >= 0 && xValTop <= w)
{
intersections.Add(new Point(xValTop, h));
}
// Check for intersection with bottom (y=0).
var xValBottom = (0.0 - b) / m;
if (xValBottom >= 0 && xValBottom <= w)
{
intersections.Add(new Point(xValBottom, 0));
}
}
return intersections;
}
And here are the tests to make sure it works:
[TestMethod]
public void IntersectingPoints_AreCorrect()
{
// The line y=x intersects a 1x1 image at points (0, 0) and (1, 1).
var results = GetIntersectionsForImage(1.0, 0.0, 1.0, 1.0);
foreach (var p in new List<Point> { new Point(0.0, 0.0), new Point(1.0, 1.0) })
{
Assert.IsTrue(results.Contains(p));
}
// The line y=1 intersects a 2x2 image at points (0, 1), and (2, 1).
results = GetIntersectionsForImage(0.0, 1.0, 2.0, 2.0);
foreach (var p in new List<Point> { new Point(0.0, 1.0), new Point(2.0, 1.0) })
{
Assert.IsTrue(results.Contains(p));
}
}