用数组绘制线条

时间:2015-11-05 14:19:18

标签: c# arrays wpf line paint

我正在开发一个应用程序,我需要在Canvas上绘制线条,这些线条需要在一个数组中,所以我仍然可以添加更改(可调整大小和颜色)。我正在尝试建立类似油漆的功能。

这是我的代码

private void w_Canvas_MouseMove(object sender, MouseEventArgs e)
{
    if (isDrawing)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            //lineStartPoint = e.GetPosition(w_Canvas);
            //Thread.Sleep(2);

            Line[] l = new Line[999999];
            for (int d = 0; d < 999999; d++)
            {
                Point lineStartPoint = e.GetPosition(w_Canvas);

                l[d].X1 = lineStartPoint.X;
                l[d].Y1 = lineStartPoint.Y;

                Thread.Sleep(1);
                Point lineEnd = e.GetPosition(w_Canvas);
                l[d].X2 = lineEnd.X;
                l[d].Y2 = lineEnd.Y;

                l[d].Stroke = brush;
                l[d].StrokeThickness = 3;
                //lineStartPoint = lineEnd;
                //probeert ee nproperty the accessen warvan de property 0 is
            }
            DrawLines(l);
        }
    }
}

private void DrawLines(Line[] l)
{
    foreach (Line line in l)
    {
        w_Canvas.Children.Add(line);
    }
}

private void w_Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
    isDrawing = false;
}

目前我收到一个'System.NullReferenceException',其中对象引用没有安装在对象的副本上。

3 个答案:

答案 0 :(得分:3)

您尝试访问l[d],但未初始化,请添加

l[d] = new Line();

在你的for循环中。

答案 1 :(得分:1)

您必须在数组中创建每一行的实例。

    Line[] l = new Line[999999];
    for (int d = 0; d < 999999; d++)
    {
       l[d] = new Line();
    }

答案 2 :(得分:0)

感谢我得到了一些帮助

private void w_Canvas_MouseMove(object sender, MouseEventArgs e)
    {
        if (isDrawing)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                Point lineEnd = e.GetPosition(w_Canvas);
                Line l = new Line();

                LINE.Add(new Tuple<double, double, double, double>(lineStartPoint.X, lineStartPoint.Y, lineEnd.X, lineEnd.Y));

                l.X1 = LINE[LINE.Count - 1].Item1;
                l.Y1 = LINE[LINE.Count - 1].Item2;
                l.X2 = LINE[LINE.Count - 1].Item3;
                l.Y2 = LINE[LINE.Count - 1].Item4;

                l.Stroke = brush;
                l.StrokeThickness = 3;
                w_Canvas.Children.Add(l);
                lineStartPoint = lineEnd;
            }
        }
    }

    private void w_Canvas_MouseUp(object sender, MouseButtonEventArgs e)
    {
        isDrawing = false;
    }

}

}

谢谢大家的帮助!