按行顺序连接点

时间:2016-12-15 11:38:21

标签: c# winforms list drawing

我真的需要一些帮助。我试图创建一个类似于游戏的程序" 连接点",其中有点数字来自(1 ... n + 1)你需要用线连接它们。 所以我有一个面板,我从文件中读取点的坐标。但是我被卡住了,因为我无法弄清楚如何将这些点与线连接起来。

My current outcome

总结一下我想做的事情:

  • 按第1点,按第2点,然后用线连接,否则不连接。
  • 并且您需要按照从1到n + 1的顺序对齐点。 我希望你能理解我。坦克提前很多!!
   private void panel1_Paint(object sender, PaintEventArgs e)
    {
        List<String> pav1;
        pav1 = new List<String>();
        StreamReader datafile = new StreamReader("pav1.txt");

    int[] X = new int[100];
    int[] Y = new int[100];
    int k = 0;
    string line;

    while (datafile.Peek() >= 0)
    {
        line = datafile.ReadLine();
        X[k] = Int16.Parse(line);
        line = datafile.ReadLine();
        Y[k] = Int16.Parse(line);
        k++;
    }
    datafile.Close();
    Brush aBrush = (Brush)Brushes.Black;
    for (int i = 0; i < k; i++)
    {
        e.Graphics.FillEllipse(aBrush, X[i], Y[i], 10, 10);
        e.Graphics.DrawString((i + 1).ToString(), new Font("Arial", 10),
              System.Drawing.Brushes.Gray, new Point(X[i] + 20, Y[i]));
    }

}

2 个答案:

答案 0 :(得分:0)

使用Graphics.Draw()方法,我不知道你为什么要使用椭圆绘图。你的循环应该看起来像

var myFont = new Font("Arial", 10);
for (int i = 0; i < k; i += 2)
{
    var point1 = new Point(X[i], Y[i]);
    var point2 = new Point(X[i + 1], Y[i + 1]);
    e.Graphics.DrawLine(aBrush, point1, point2);
    e.Graphics.DrawString((i + 1).ToString(), myFont, System.Drawing.Brushes.Gray, point1);
    e.Graphics.DrawString((i + 2).ToString(), myFont, System.Drawing.Brushes.Gray, point2);
}

此外,点0, 0位于左上角。

答案 1 :(得分:0)

首先,从panel_paint方法中取出点,并添加其他属性,如序数。因此,不应该使用数组X []和Y [],而应该像这样创建类:

public class Dot
{
    public Point Coordinates { get; set; }
    public int Ordinal { get; set; }
}

然后

List<Dot> Dots { get; set; }

为第一个和第二个选定的点制作两个道具

private Dot FirstDot { get; set; }
private Dot SecondDot { get; set; }

按照您填充X[]Y[]数组的相同方式填写该列表。

然后在面板上添加OnMouseClick处理程序,并在其中写下如下内容:

    private void panel1_MouseClick(object sender, MouseEventArgs e)
    {
        //check if user clicked on any of dots in list
        var selectedDot = Dots.FirstOrDefault(dot => e.X < dot.Coordinates.X + 10 && e.X > dot.Coordinates.X
            && e.Y < dot.Coordinates.Y + 10 && e.Y > dot.Coordinates.Y);

        //dot is found, add it to selected first or second dot property
        if (selectedDot != null)
        {
            if (FirstDot == null)
                FirstDot = selectedDot;
            else if (SecondDot == null)
                SecondDot = selectedDot;
        }   

    }

现在,在你的绘画方法中,你应该检查两个点是否都已设置,如果是,请检查它们是否与其他点相邻,如

if (FirstDot.Ordinal + 1 == SecondDot.Ordinal)

然后你可以使用

绘制线条
e.Graphics.DrawLine(aBrush, FirstDot.Coordinates, SecondDot.Coordinates);

那应该是它。我希望你了解如何实现它的方式。除了几张支票,应该是它。