The SDL forums have moved to discourse.libsdl.org.
This is just a read-only archive of the previous forums, to keep old links working.
SDL
Simple Directmedia Layer Forums
Progress Bars (Health bars, etc..)
MikeyPro
Joined: 14 Feb 2015
Posts: 15
Posted: Sat Feb 21, 2015 6:06 pm
Hey. Hi. I just added these to my codebase and figured they're so awesome and genius that I had to come on the sdl forums to gloat about it.
Seriously though, if you needed some simple health bars/progress bars and are too lazy to code them in the 5 minutes it takes, here take these, they're free:
Code:
/*
Render a Horizontal Percentage Bar
Drains left to right normally, if width is negative it will drain right to left.
Percent is clamped 0.0f - 1.0f
*/
void RenderHPBar(int x, int y, int w, int h, float Percent, SDL_Color FGColor, SDL_Color BGColor) {
Percent = Percent > 1.f ? 1.f : Percent < 0.f ? 0.f : Percent;
SDL_Color old;
SDL_GetRenderDrawColor(Renderer, &old.r, &old.g, &old.g, &old.a);
SDL_Rect bgrect = { x, y, w, h };
SDL_SetRenderDrawColor(Renderer, BGColor.r, BGColor.g, BGColor.b, BGColor.a);
SDL_RenderFillRect(Renderer, &bgrect);
SDL_SetRenderDrawColor(Renderer, FGColor.r, FGColor.g, FGColor.b, FGColor.a);
int pw = (int)((float)w * Percent);
int px = x + (w - pw);
SDL_Rect fgrect = { px, y, pw, h };
SDL_RenderFillRect(Renderer, &fgrect);
SDL_SetRenderDrawColor(Renderer, old.r, old.g, old.b, old.a);
}
/*
Render a Vertical Percentage Bar
Drains top to bottom normally, if height is negative it will drain bottom to top
Percent is clamped 0.0f - 1.0f
*/
void RenderVPBar(int x, int y, int w, int h, float Percent, SDL_Color FGColor, SDL_Color BGColor) {
Percent = Percent > 1.f ? 1.f : Percent < 0.f ? 0.f : Percent;
SDL_Color old;
SDL_GetRenderDrawColor(Renderer, &old.r, &old.g, &old.g, &old.a);
SDL_Rect bgrect = { x, y, w, h };
SDL_SetRenderDrawColor(Renderer, BGColor.r, BGColor.g, BGColor.b, BGColor.a);
SDL_RenderFillRect(Renderer, &bgrect);
SDL_SetRenderDrawColor(Renderer, FGColor.r, FGColor.g, FGColor.b, FGColor.a);
int ph = (int)((float)h * Percent);
int py = y + (h - ph);
SDL_Rect fgrect = { x, py, w, ph };
SDL_RenderFillRect(Renderer, &fgrect);
SDL_SetRenderDrawColor(Renderer, old.r, old.g, old.b, old.a);
}
It wouldn't be too much more work to modify these to use textures instead, hint hint.
Also, you may want this if you haven't made one already and you're truly lazy, like I am. I mean, it's like three lines.. Whatever.. Here:
Code:
/*
color - Returns an SDL_Color with the appropriate values
*/
SDL_Color color(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
SDL_Color col = {r,g,b,a};
return col;
}