Skip to content

Instantly share code, notes, and snippets.

@DarkStar1997
Last active October 30, 2021 15:47
Show Gist options
  • Save DarkStar1997/8f2d8b8c53e3f7bce705d02c180378f9 to your computer and use it in GitHub Desktop.
Save DarkStar1997/8f2d8b8c53e3f7bce705d02c180378f9 to your computer and use it in GitHub Desktop.
Progress bar with fmt
#include <fmt/core.h>
#include <fmt/color.h>
#include <chrono>
#include <thread>
void update_bar(int percent)
{
int total = 100;
int done = (percent / 100.0) * total;
fmt::print("\r[");
fmt::print(fg(fmt::rgb(5, 16, 57)) | bg(fmt::rgb(78, 66, 193)) | fmt::emphasis::bold, "{:>>{}}", "", done);
fmt::print(fg(fmt::color::dark_blue) | bg(fmt::color::black), "{:->{}}", "", total - done);
fmt::print("]");
fmt::print(fg(fmt::color::sky_blue) | fmt::emphasis::bold, " {:>2}%", percent);
fflush(stdout);
}
void update_transition_bar(int percent,
const fmt::rgb& start = fmt::color::white,
const fmt::rgb &finish = fmt::color::black)
{
int total = 100;
float alpha = percent / 100.0;
int done = alpha * total;
fmt::rgb bg_color = fmt::rgb((1 - alpha) * start.r + alpha * finish.r,
(1 - alpha) * start.g + alpha * finish.g,
(1 - alpha) * start.b + alpha * finish.b);
fmt::print("\r[");
fmt::print(fg(fmt::rgb(5, 16, 57)) | bg(bg_color) | fmt::emphasis::bold, "{:>>{}}", "", done);
fmt::print(fg(fmt::color::dark_blue) | bg(fmt::color::black), "{:->{}}", "", total - done);
fmt::print("]");
fmt::print(fg(fmt::color::sky_blue) | fmt::emphasis::bold, " {:>2}%", percent);
fflush(stdout);
}
void update_gradient_bar(int percent,
const fmt::rgb& start = fmt::color::white,
const fmt::rgb &finish = fmt::rgb(72, 184, 79))
{
int total = 100;
int done = (percent / 100.0) * total;
fmt::print("\r[");
for(int i = 1; i <= done; i++)
{
float alpha = i / 100.0;
fmt::rgb bg_color = fmt::rgb((1 - alpha) * start.r + alpha * finish.r,
(1 - alpha) * start.g + alpha * finish.g,
(1 - alpha) * start.b + alpha * finish.b);
fmt::print(fg(fmt::rgb(5, 16, 57)) | bg(bg_color) | fmt::emphasis::bold, ">");
}
fmt::print(fg(fmt::color::dark_blue) | bg(fmt::color::black), "{:->{}}", "", total - done);
fmt::print("]");
fmt::print(fg(fmt::color::sky_blue) | fmt::emphasis::bold, " {:>2}%", percent);
fflush(stdout);
}
int main(int argc, char **argv)
{
char ch = 0;
if(argc > 1)
ch = argv[1][0];
int done = 0, total = 100;
while(done <= total)
{
if(ch == 0 || ch == 'n')
{
update_bar((done++ / (float)total) * 100);
}
else if(ch == 't')
{
update_transition_bar((done++ / (float)total) * 100);
}
else if(ch == 'g')
{
update_gradient_bar((done++ / (float)total) * 100);
}
std::this_thread::sleep_for(std::chrono::milliseconds(17));
}
fmt::print("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment