Search code examples
.netc++-clipen

.net drawlines with pens(different colors) in a loop


I want to draw lines ( about 100 ) with different colors. The lines will draw in a loop and get random colors. Here is my code:

for( int i = 0; i < 100 < i++ )
{
srand( time(NULL) );
int index = rand() % 99;
Pen^  my_pen = gcnew Pen((Color)CustomColorTables[index]);
g->drawLine(my_pen,startPointAray[i],stopPointArray[i]);
}

But it draws all lines with the same color???

Note: I checked the random values, there is no problem about generating random values.


Solution

  • Try to place the line:

    srand( time(NULL) );
    

    BEFORE entering the for loop. In your case you are resetting each time the pseudo random sequence and you probably obtain a wrong sequence. Then use:

    int index = (100*rand()) % 99;
    

    because rand() by itself returns a number from 0 to 1 and you will always receive 99 as a % result.