Shape color change constantly

I want my program to constantly change the background color of the font, but I want it to go smoothly, so I tried to change the color Color custom; variable Color custom; and use it for the background color of the form this.BackColor = custom; but this is not so. I work and I don’t know how to make it work, here is the full code:

 private void Principal_Load(object sender, EventArgs e) { Color custom; int contr = 0, contg = 0, contb = 0; do { while (contr < 255 && contg == 0) { if (contb != 0) { contb--; } contr++; while (contg < 255 && contb == 0) { if (contr != 0) { contr--; } contg++; while (contb < 255 && contr == 0) { if (contg != 0) { contg--; } contb++; } } } custom = Color.FromArgb(contr, contg, contb); this.BackColor = custom; } while (true); } 
+6
source share
2 answers

For starters, your current code does not work, but not because of any thread problem (although this needs to be resolved).

The problem is that these lines never get in:

 custom = Color.FromArgb(contr, contg, contb); this.BackColor = custom; 

The logic in your while loops just doesn't work.

The values ​​you produce are a set:

 (0, 0, 1), (0, 0, 2) ... (0, 0, 255), (0, 254, 1), (0, 253, 2) ... (0, 1, 254) 

Then it simply repeats attempts to produce these values, but can never break out of the while (contr < 255 && contg == 0) .

Now, assuming that what you really want, I suggest that the best approach to this is to use the Microsoft Reactive Framework. Just NugGet "Rx-WinForms" and you can write this code:

 var ranges = new[] { Observable.Range(1, 255).Select(x => Color.FromArgb(0, 0, x)), Observable.Range(1, 254).Select(x => Color.FromArgb(0, 255 - x, x)), }; var query = ranges .Concat() .Zip(Observable.Interval(TimeSpan.FromMilliseconds(100.0)), (x, i) => x) .Repeat() .ObserveOn(this); var subscription = query.Subscribe(c => this.BackColor = c); 

So ranges - an array of IObservable<Color> . Calling .Concat() on ranges turns it from IObservable<Color>[] to IObservable<Color> . .Zip associates each value with a timer counting down in increments of 10 ms (you can change the value if you want). The .Repeat() call simply repeats the loop continuously - sort of like while (true) . Then .ObserveOn(this) causes the observed subscription to run in the user interface thread.

Finally, .Subscribe(...) actually launches the observable and updates the BackColor form.

The best part is that you can stop the subscription at any time by calling .Dispose() in the subscription:

 subscription.Dispose(); 

This clears all threads and the timer. This is a very neat solution.

+1
source

Very simply, you have no delays. because of this link add

 Thread.Sleep(1000); 

all this must happen in a separate thread! or your user interface will be stuck

Check it out

+5
source

Source: https://habr.com/ru/post/987846/


All Articles