Search code examples
c#listlinedrawrectangle

How to connect two points from a DrawRectangle with a line?


How would one go about achieving a line that will connect two rectangles together? At the moment, I have this:

if (listBox1.Items.Count >= 2)
{
    e.Graphics.DrawLine(Pens.AliceBlue, new Point(/*??*/), new Point(n._x, n._y));                    
}

With the second new Point being where I placed my new Rectangle but I am not sure how to get the point of the Rectangle beforehand.

My rectangles X and Y are stored in a list like so:

public BindingList<Node> nodeList = new BindingList<Node>();

My main goal would be too add a line to each of my rectangles as they are drawn.

For example: Place one rectangle down, nothing happens, place another one down, add a line connecting the two, add a third, add a line connecting the second and third one together. But if I can get one going I can try and work out how to continuously add these lines.

Thanks for any help!


Solution

  • If you have a list of Rectangles, you can draw them with lines connecting them like this:

    void drawRectangles(Graphics g, List<Rectangle> list) {
        if (list.Count == 0) {
            return;
        }
    
        Rectangle lastRect = list[0];
        g.DrawRectangle(Pens.Black, lastRect);
    
        // Indexing from the second rectangle -- the first one is already drawn!
        for (int i = 1; i < list.Count; i++) {
            Rectangle newRect = list[i];
            g.DrawLine(Pens.AliceBlue, new Point(lastRect.Right, lastRect.Bottom), new Point(newRect.Left, newRect.Top));
            g.DrawRectangle(Pens.Black, newRect);
            lastRect = newRect;
        }
    }
    

    You may insert some smart code to decide which corners to connect, but that's up to you.