I'm working on coloring a component based on the time since its last update. I would like it to start green, then slowly get red, reaching completely red in (oh, say) 10 seconds. That time length is arbitrary though and I'd consider solutions that infinitely approach red. So my proposed pseudocode looks something like this:
Code:
//Get the amount of time between now and the last time it was updated
Timespan t = Datetime.Now - LastUpdate;
//Get the number of seconds that represents
int NumberOfSeconds = Convert.ToInt32(Timespan.Seconds);
//If the number is higher than 10, make it 10 (because we're not getting redder than red)
if (NumberOfSeconds > 10) NumberOfSeconds = 10;
//Return a color based on the number of seconds
switch
{
Case 1:
return Color.Green;
Case 2:
return Color.SomewhatLessGreen;
Case 3:
return Color.EvenLessGreen;
Case 4:
return Color.GreenWithSomePink;
Case 5:
return Color.HalfGreenHalfRed;
Case 6:
return Color.SomewhatMorePinkThanGreen;
Case 7:
return Color.EvenMoreRed;
Case 8:
return Color.FairlyRed;
Case 9:
return Color.AlmostCompletelyRed;
Case 10:
return Color.Red;
Case default:
return Color.Red;
}
So I have a method that words, but it's messy and ugly and hard to change/maintain... and I can't help the feeling that there's a MUCH better way to go about this. Anybody have a suggestion?
I ended up solving my own problem... if anybody else encounters it, here is the code I used:
Code:
//This is the amount of time it takes to get completely red from a green starting state
const int ci_SecondsToRed = 20;
public DateTime LastSuccessfulPing;
public Color GetStatusColor()
{
TimeSpan t = DateTime.Now - LastSuccessfulPing;
//Get the number of seconds that represents
int NumberOfSeconds = Convert.ToInt32(t.Seconds);
//If the number is higher than ci_SecondsToRed, make it ci_SecondsToRed (because we're not getting redder than red)
if (NumberOfSeconds > ci_SecondsToRed) NumberOfSeconds = ci_SecondsToRed;
//Return a color that goes from green to red over the constant number of seconds
return Color.FromArgb((255/ci_SecondsToRed)*NumberOfSeconds,(255/ci_SecondsToRed)*(ci_SecondsToRed-NumberOfSeconds),0);
}
R, G, and B elements of a color are bytes, so can hold numbers from 0 to 255.
Set increment to 255/<number of desired steps from Green to Red>
<code>
// Example 10 steps from Green to Red
byte increment = 255/10;
for (byte i = 0; i < (byte)0x0b; i++)
{
System.Drawing.Color thisColor = getNextColor(thisColor, increment);
}
Bookmarks