Search code examples
c#colorsfading

Looking for help in C# with RGB color cross fade


Ok, I made an app in C# that polls info from my screen for ambilight SFX using an external LED controller. My question is, what is the code or how do I go about making a color cross fade type thing where I get a fade from red to green to blue and out put the RGB values as

red = CODE;
green = CODE; 
blue = CODE;

I have done this long ago in C++ using "Interpolation(FadeSteps, Delay, Array)", I just don't have a clue how in C#

Think of drawing a 2D box and have it fade from one color to the next that's the idea.

I just want to be able to set speed of the fade
Idea as to what it's controlling


Solution

  • Ok, If I understand you right, you want to fade from Red, to green to blue?

    Starting off with a struct and an enum to hold our color data and state.

    public enum PrimaryColor
    {
        Red,
        Green,
        Blue
    }
    
    public struct Color
    {
        public byte r;
        public byte g;
        public byte b;
    
        public Color(byte r, byte g, byte b)
        {
            this.r = r;
            this.g = g;
            this.b = b;
        }
    }
    

    We then make some variables to hold our state data, including an array of which we will traverse.

    Color ActualColor = new Color(255, 0, 0);
    int State = 0;
    PrimaryColor[] Order = { PrimaryColor.Red, PrimaryColor.Green, PrimaryColor.Blue };
    

    Then, in your update function (say a timer, or while loop, etc.) we add a little switch statement to update colors, check for byte underflow and change states.

    switch (Order[State])
    {
        case PrimaryColor.Red:
            ActualColor.r++;
            if(ActualColor.g > 0) ActualColor.g--;
            if (ActualColor.b > 0) ActualColor.b--;
            if (ActualColor.r == 255 && ActualColor.g == 0 && ActualColor.b == 0) State++;
            break;
        case PrimaryColor.Green:
            ActualColor.g++;
            if (ActualColor.r > 0) ActualColor.r--;
            if (ActualColor.b > 0) ActualColor.b--;
            if (ActualColor.r == 0 && ActualColor.g == 255 && ActualColor.b == 0) State++;
            break;
        case PrimaryColor.Blue:
            ActualColor.b++;
            if (ActualColor.g > 0) ActualColor.g--;
            if (ActualColor.r > 0) ActualColor.r--;
            if (ActualColor.r == 0 && ActualColor.g == 0 && ActualColor.b == 255) State++;
            break;
        default:
            break;
    }
    if (State == Order.Length) State = 0;
    
    //Send color data to your controller