-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathText.cpp
More file actions
62 lines (51 loc) · 1.52 KB
/
Text.cpp
File metadata and controls
62 lines (51 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "Text.hpp"
Text::Text(GameWindow* gw, const std::string& text, const int& x, const int& y, const int& font_size)
: game_window(gw),
text(text), x(x), y(y),
font(TTF_OpenFont("font.ttf", font_size))
{
if (font == nullptr)
throw Error("Font not found.");
init();
}
Text::~Text()
{
TTF_CloseFont(font);
}
// NOTE: Rather "prepare to render". After calling render() on Text obj, you must call SDL_RenderPresent to display text.
void Text::render() const
{
SDL_SetRenderDrawColor(game_window->renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderCopy(game_window->renderer, texture, nullptr, &rect);
// Call SDL_RenderPresent(game_window->renderer); to display !
}
void Text::move_left_side_text()
{
SDL_Surface* surface;
SDL_Color textColor = {0xFF, 0xFF, 0xFF, 0};
surface = TTF_RenderText_Solid(font, text.c_str(), textColor);
x -= surface->w;
SDL_FreeSurface(surface);
surface = nullptr;
}
void Text::init()
{
SDL_Surface* surface;
SDL_Color textColor = {0xFF, 0xFF, 0xFF, 0};
surface = TTF_RenderText_Solid(font, text.c_str(), textColor);
texture = SDL_CreateTextureFromSurface(game_window->renderer, surface);
if (texture == nullptr)
throw Error("Creating a texture from an existing surface failed. " + std::string(SDL_GetError()));
rect.x = x;
rect.y = y;
rect.w = surface->w;
rect.h = surface->h;
// check if text is on the left side from the game_window middle, if yes - it must be moved
if (x < game_window->width / 2)
{
x -= rect.w;
rect.x -= rect.w;
}
SDL_FreeSurface(surface);
surface = nullptr;
}