.net drawlines with pens(different colors) in a loop
Question
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.
OTHER TIPS
try to replace:
CustomColorTables[index];
with:
CustomColorTables[i];
if it works better than before as I believe, the issue is in the way you generate and use the random value index.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow