如何实现将两个矩形连接在一起的线?目前,我有这个:
if (listBox1.Items.Count >= 2)
{
e.Graphics.DrawLine(Pens.AliceBlue, new Point(/*??*/), new Point(n._x, n._y));
}
第二个新Point是我放置新Rectangle的地方,但我不知道如何预先获得Rectangle的点。
我的矩形X和Y存储在如下列表中:
public BindingList<Node> nodeList = new BindingList<Node>();
我的主要目标是在绘制时为每个矩形添加一条线。
例如:放下一个矩形,没有任何反应,放下另一个矩形,添加连接两个的线,添加第三个,添加连接第二个和第三个的线。但是,如果我能够继续前进,我可以尝试找出如何不断添加这些线。
感谢您的帮助!
答案 0 :(得分:0)
如果您有一个矩形列表,您可以使用连接它们的线条绘制它们,如下所示:
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;
}
}
您可以插入一些智能代码来决定要连接的角落,但这取决于您。
答案 1 :(得分:0)
仅适用于可能需要此代码示例的任何其他人。 for循环应该从0开始。所以;
for (int i = 1; i < list.Count; i++)
{
//Code here
}
应该是:
for (int i = **0**; i < list.Count; i++)
{
//Code here
}