DungeonMaster3000
DungeonMaster3000

Reputation: 21

WPF Draw Lines in a loop only seems to draw one line

I'm trying to draw several lines to the canvas within a for loop but only seems to be drawing one. What am I doing wrong?

for (int x = 0; x < 10; x++)
        {
            Random rand = new Random();
            double newTop = rand.Next(0, 50);


            Line top = new Line();
            top.Stroke = Brushes.Black;
            top.StrokeThickness = 2;
            top.Width = 50;

            top.X1 = x * top.Width;
            top.Y1 = 0;
            top.X2 = x * top.Width + top.Width;
            top.Y2 = newTop;

            Canvas.SetTop(top, 0);
            Canvas.SetLeft(top, x * top.Width);
            TheCanvas.Children.Add(top);
        }

thanks, Tarran

Upvotes: 0

Views: 1097

Answers (2)

AlexD
AlexD

Reputation: 32576

You may get the same value from random generator every time:

The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers."

See Random Constructor.

I'd suggest to move the line

Random rand = new Random();

in front of the loop.


Also, it seems that from the second step you are drawing outside of canvas. Try the following code instead:

Random rand = new Random();
for (int x = 0; x < 10; x++)
{
    double newTop = rand.Next(0, 50);

    Line top = new Line();
    top.Stroke = Brushes.Black;
    top.StrokeThickness = x + 1;
    top.Width = 500;

    int width = 50;
    top.X1 = x * width;
    top.Y1 = 0;
    top.X2 = x * width + width;
    top.Y2 = newTop;

    Canvas.SetTop(top, 0);
    Canvas.SetLeft(top, 0 /*x * top.Width*/);
    TheCanvas.Children.Add(top);
}

Upvotes: 4

cost
cost

Reputation: 4480

You're drawing the same line over and over, you need to seed the random number with something different.

Random rand = new Random(Guid.NewGuid().GetHashCode());

Your other option is to move the random creation outside of your loop, and use Next, like you have. I'd suggest using this option:

Random rand = new Random();

for (int x = 0; x < 10; x++)
    {
        double newTop = rand.Next(0, 50);

        Line top = new Line();
        top.Stroke = Brushes.Black;
        top.StrokeThickness = 2;
        top.Width = 50;

        top.X1 = x * top.Width;
        top.Y1 = 0;
        top.X2 = x * top.Width + top.Width;
        top.Y2 = newTop;

        Canvas.SetTop(top, 0);
        Canvas.SetLeft(top, x * top.Width);
        TheCanvas.Children.Add(top);
    }

This will prevent the Random from being re-seeded every time.

Upvotes: 0

Related Questions