a function that uses bresenham's line algorithm to take two points and returns an array of points that represent the line in csharp

main.cs
public static List<Point> BresenhamLine(Point point1, Point point2)
{
    List<Point> points = new List<Point>();
    
    int x1 = point1.X;
    int y1 = point1.Y;
    int x2 = point2.X;
    int y2 = point2.Y;
    
    int dx = Math.Abs(x2 - x1);
    int dy = Math.Abs(y2 - y1);
    
    int sx = x1 < x2 ? 1 : -1;
    int sy = y1 < y2 ? 1 : -1;
    
    int err = dx - dy;
    
    points.Add(new Point(x1, y1));
    
    while (x1 != x2 || y1 != y2)
    {
        int e2 = 2 * err;
        
        if (e2 > -dy)
        {
            err -= dy;
            x1 += sx;
        }
        
        if (e2 < dx)
        {
            err += dx;
            y1 += sy;
        }
        
        points.Add(new Point(x1, y1));
    }
    
    return points;
}
756 chars
41 lines

This function takes in two Point objects representing the start and end points of the line. It then uses Bresenham's line algorithm to calculate all the points along the line between the two points, and returns them as a List<Point>.

Note: This implementation assumes that the two points are in the same quadrant. If they are in different quadrants, additional logic will be required.

gistlibby LogSnag