0

I'm working on an app where I need to draw lines on Canvas, these lines need to be in an array so I can still add changes to it (Resizeable and color). I'm trying to build a paint-like function.

This is my code

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;
}

Currently I'm getting a 'System.NullReferenceException' where an object reference isn't installed on a copy of an object.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92

3 Answers3

3

You try to access to l[d] but it's not initialized, add

l[d] = new Line();

In your for loop.

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
1

You have to create an instance of each line in the array.

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

Thanks to some help i got it

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;
    }

}

}

Thank you all for your help also!