Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add static method for converting RGB to HSV #335

Open
TBog opened this issue Oct 18, 2022 · 1 comment
Open

Add static method for converting RGB to HSV #335

TBog opened this issue Oct 18, 2022 · 1 comment

Comments

@TBog
Copy link

TBog commented Oct 18, 2022

I was testing different animations and found that I needed to convert a RGB color to make a fade animation of it by changing the brightness.
There is no function to do this and because most code samples use hue as a float or unit8_t I couldn't copy-paste the solution.
I came up with this function:

void RgbToHsv(uint8_t r, uint8_t g, uint8_t b, uint16_t &h, uint8_t &s, uint8_t &v)
{
    uint8_t rgbMin, rgbMax;

    rgbMin = r < g ? (r < b ? r : b) : (g < b ? g : b);
    rgbMax = r > g ? (r > b ? r : b) : (g > b ? g : b);

    v = rgbMax;
    if (v == 0)
    {
        h = 0;
        s = 0;
        return;
    }

    s = 255 * static_cast<uint16_t>(rgbMax - rgbMin) / v;
    if (s == 0)
    {
        h = 0;
        return;
    }

    if (rgbMax == r)
        h = 65535 / 3 * 0 + 65535 / 6 * static_cast<int>(g - b) / (rgbMax - rgbMin);
    else if (rgbMax == g)
        h = 65535 / 3 * 1 + 65535 / 6 * static_cast<int>(b - r) / (rgbMax - rgbMin);
    else
        h = 65535 / 3 * 2 + 65535 / 6 * static_cast<int>(r - g) / (rgbMax - rgbMin);
}

Should I make a PR for this or just leave it here for anyone else that may need this functionality?

@ajschwieterman
Copy link

Make a PR for this. It would be a great addition to the library!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants