File: text_renderer.c

package info (click to toggle)
vonsh 1.0
  • links: PTS
  • area: main
  • in suites: bullseye, sid
  • size: 2,420 kB
  • sloc: ansic: 958; makefile: 37
file content (71 lines) | stat: -rw-r--r-- 1,832 bytes parent folder | download
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
63
64
65
66
67
68
69
70
71
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "text_renderer.h"
#include "font_layout.h"

static SDL_Renderer* text_renderer = NULL;
static SDL_Texture* font_texture = NULL;
static int font_h = 0; /* font texture height */

void init_text_renderer(SDL_Renderer* renderer, SDL_Texture* texture) {
    text_renderer = renderer;
    font_texture = texture;
    SDL_QueryTexture(font_texture, NULL, NULL, NULL, &font_h);
}

void set_text_color(uint8_t r, uint8_t g, uint8_t b) {
    SDL_SetTextureColorMod(font_texture, r, g, b);
}

int render_text(int x, int y, TextAlignment align, char *text) {
    int i; /* index of letter font layout table */
    char *text_p = NULL;
    int text_w = 0; /* text width */
    SDL_Rect SrcR, DstR;

    SrcR.y = 0;
    DstR.y = y;
    SrcR.h = DstR.h = font_h;

    /* calculate text width, needed for correct Right and Center alignments */
    text_p = text;
    while(*text_p) {
        if (*text_p != ' ') {
            i = *text_p - '!';
            text_w += font_layout[i+1] - font_layout[i];
        }
        else {
            text_w += font_h/3; /* substitute for space */
        }
        text_p++;
    }

    /* start position of text */
    if (align == Right) {
        DstR.x = x - text_w;
    }
    else if (align == Center) {
        DstR.x = x - text_w/2;
    }
    else {
        DstR.x = x;
    }

    /* Render text */
    text_p = text;
    while(*text_p) {
        if (*text_p != ' ') {
            i = *text_p - '!';
            SrcR.x = font_layout[i];
            SrcR.w = DstR.w = font_layout[i+1] - font_layout[i];
            SDL_RenderCopy(text_renderer, font_texture, &SrcR, &DstR);
            DstR.x += DstR.w;
        }
        else {
            DstR.x += font_h/3; /* substitute for space */
        }
        text_p++;
    }

    return text_w;
}