graphics - C# Drawing, Strange Behaviour -
the following code straight forward - fills design surface randomnly selected pixels - nothing special (ignore xxxxxxx's in 2nd method now).
private void paintbackground() { random rnd = new random(); bitmap b = new bitmap(this.width, this.height); (int vertical = 0; vertical < this.height; vertical++) { (int horizontal = 0; horizontal < this.width; horizontal++) { color randomcolour = getrandomcolor(rnd); b.setpixel(horizontal, vertical, randomcolour); } } graphics g = this.creategraphics(); g.drawimage(b, new point(0, 0)); } public color getrandomcolor(random rnd) { xxxxxxxxxxxxxxxx byte r = convert.tobyte(rnd.next(0, 255)); byte g = convert.tobyte(rnd.next(0, 255)); byte b = convert.tobyte(rnd.next(0, 255)); return color.fromargb(255, r, g, b); }
the question have this...
if replace xxxxxxxxx "random rnd = new random();" test pattern changes horizontal bars of same colour, , therefore not random.
come explain me why is?
as far can tell difference in second attempt getrandomcolour method creates , uses new instance of random class don't see how makes horizontal bars..
from msdn:
the random number generation starts seed value. if same seed used repeatedly, same series of numbers generated. 1 way produce different sequences make seed value time-dependent, thereby producing different series each new instance of random. default, the parameterless constructor of random class uses system clock generate seed value, while parameterized constructor can take int32 value based on number of ticks in current time. however, because clock has finite resolution, using parameterless constructor create different random objects in close succession creates random number generators produce identical sequences of random numbers. following example illustrates 2 random objects instantiated in close succession generate identical series of random numbers.
so given same seed random instance produce same sequence of numbers. , in example due finite resolution of system clock, random instances created using same tick count seed, resulting in same sequence.
the consecutive calls getrandomcolor()
executed within 1 time slice of system clock. test this, try slowing method down thread.sleep(1)
. should see different colors being generated.
Comments
Post a Comment