To change the color of rendered text in SDL2 using SDL_ttf, you can modify the SDL_Color
parameter passed to the text rendering function.
Here's one way you can do it. First, create an SDL_Color
structure with the desired RGBÂ values:
// Red color (R, G, B)
SDL_Color textColor = {255, 0, 0};
Pass this color to the text rendering function. For example, if you're using TTF_RenderUTF8_Blended()
:
SDL_Surface* textSurface {
TTF_RenderUTF8_Blended(
font,
"Hello, colorful world!",
textColor
)
};
Here's a more complete example that demonstrates changing text color:
#include <SDL.h>
#include <SDL_ttf.h>
#include <iostream>
class Text {
public:
Text(TTF_Font* font,
const std::string& content,
SDL_Color color)
: m_font(font), m_content(content),
m_color(color) { updateSurface(); }
void setColor(SDL_Color newColor) {
m_color = newColor;
updateSurface();
}
void render(SDL_Surface* destinationSurface,
int x, int y) {
if (m_surface) {
SDL_Rect destRect = {
x, y, m_surface->w, m_surface->h};
SDL_BlitSurface(m_surface, nullptr,
destinationSurface,
&destRect);
}
}
~Text() {
if (m_surface) {
SDL_FreeSurface(m_surface);
}
}
private:
void updateSurface() {
if (m_surface) {
SDL_FreeSurface(m_surface);
}
m_surface = TTF_RenderUTF8_Blended(
m_font, m_content.c_str(), m_color);
if (!m_surface) {
std::cerr << "Failed to render text: " <<
TTF_GetError() << '\n';
}
}
TTF_Font* m_font;
std::string m_content;
SDL_Color m_color;
SDL_Surface* m_surface = nullptr;
};
int main() {
// Initialize SDL and TTF
// ...
TTF_Font* font = TTF_OpenFont(
"path/to/font.ttf", 24);
if (!font) {
std::cerr << "Failed to load font: " <<
TTF_GetError() << '\n';
return 1;
}
Text redText(font, "Hello, Red!",
{255, 0, 0});
Text blueText(font, "Hello, Blue!",
{0, 0, 255});
// Main loop
// ...
// Clean up
TTF_CloseFont(font);
TTF_Quit();
SDL_Quit();
return 0;
}
In this example, we create a Text
class that encapsulates the text rendering process. The setColor
method allows you to change the text color dynamically. Remember to call updateSurface()
after changing the color to regenerate the text surface with the new color.
By adjusting the RGB values in the SDL_Color
structure, you can create any color you need for your text. You can also include an alpha value for transparency by using an SDL_Color
with four components: {R, G, B, A}
.
Answers to questions are automatically generated and may not have been reviewed.
SDL_ttf
Learn to render and manipulate text in SDL2 applications using the official SDL_ttf
extension