Skip to content

Instantly share code, notes, and snippets.

@lennyRBLX
Created November 6, 2019 15:57
Show Gist options
  • Save lennyRBLX/49bfc7ca6501dbc687370c54b0b17be4 to your computer and use it in GitHub Desktop.
Save lennyRBLX/49bfc7ca6501dbc687370c54b0b17be4 to your computer and use it in GitHub Desktop.
A single header include for all coloring needs, can be used, easily, to create a simple rainbow effect, and convert HSV, and RGB, into hex for web design.
#pragma once
#include <Windows.h>
namespace coloring {
template< typename T >
std::string int_hex(T val) {
if (static_cast<int>(val) == 0)
return std::string("00");
char hexval[3];
sprintf(hexval, "%00x", static_cast<int>(val));
hexval[2] = 0;
return std::string(hexval);
}
std::string rgb_hex(float r, float g, float b) {
return int_hex(r) + int_hex(g) + int_hex(b);
}
class RGB_C {
public:
float r, g, b;
RGB_C() {
r = 0.f;
g = 0.f;
b = 0.f;
}
RGB_C(float nr, float ng, float nb) {
r = nr;
g = ng;
b = nb;
}
};
class HSV {
public:
float h, s, v;
HSV() {
h = 0.f;
s = 0.f;
v = 0.f;
}
HSV(float nh, float ns, float nv) {
h = nh;
s = ns;
v = nv;
}
};
RGB_C hsv_rgb(float H, float S, float V) {
H = H * 360.f; S = S * 100.f; V = V * 100.f;
float r = 0.f, g = 0.f, b = 0.f;
float h = H / 360;
float s = S / 100;
float v = V / 100;
int i = floor(h * 6);
float f = h * 6 - i;
float p = v * (1 - s);
float q = v * (1 - f * s);
float t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
RGB_C color;
color.r = floorf(r * 255.f);
color.g = floorf(g * 255.f);
color.b = floorf(b * 255.f);
return color;
}
};
// simple rainbow
int main() {
float rainbow_r = 255.f, rainbow_g = 0.f, rainbow_b = 0.f;
while (true) {
for (float i = 0.f; i < 255.f; i += 2.f) {
coloring::RGB_C rgb = coloring::hsv_rgb(i / 256, 0.6f, 1.f);
rainbow_r = rgb.r;
rainbow_g = rgb.g;
rainbow_b = rgb.b;
std::this_thread::sleep_for(std::chrono::milliseconds(25));
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment