Last active
January 1, 2024 21:27
-
-
Save Apocryphon-X/0dc0c1d77ca9bd8749027579178a730e to your computer and use it in GitHub Desktop.
Simple C++ code I adapted from Will McGugan's snippet (@ https://github.com/Textualize/rich-cli/blob/0721cb196661687d8ecd9af4baf48576b240c978/src/rich_cli/__main__.py#L145-L160)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
struct color { | |
short r; | |
short g; | |
short b; | |
}; | |
std::string as_24bit_ansi(color values) { | |
return std::string("\x1b[38;2;") | |
+ std::to_string(values.r) + ";" | |
+ std::to_string(values.g) + ";" | |
+ std::to_string(values.b) + "m"; | |
} | |
/* | |
* Adapted from Will McGugan's snippet at: | |
* https://github.com/Textualize/rich-cli/blob/0721cb196661687d8ecd9af4baf48576b240c978/src/rich_cli/__main__.py#L145-L160 | |
*/ | |
std::string add_gradient(std::string text, color first_color, color second_color) { | |
short diff_r = second_color.r - first_color.r; | |
short diff_g = second_color.g - first_color.g; | |
short diff_b = second_color.b - first_color.b; | |
std::string colorized; | |
for (int c = 0; c < (int) text.size(); c++) { | |
double gradient_factor = double(c) / double(text.size()); | |
color actual_colors = { | |
short(first_color.r + diff_r * gradient_factor), | |
short(first_color.g + diff_g * gradient_factor), | |
short(first_color.b + diff_b * gradient_factor) | |
}; | |
std::string ansi_sequence = as_24bit_ansi(actual_colors); | |
colorized += ansi_sequence; | |
colorized += text.at(c); | |
} | |
colorized += "\x1b[0m"; | |
return colorized; | |
} | |
int main() { | |
std::string sentence = "Lorem Ipsum Dolor Sit Amet."; | |
color color_1{255, 0, 0}; | |
color color_2{0, 235, 255}; | |
std::cout << add_gradient(sentence, color_1, color_2) << '\n'; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment