aboutsummaryrefslogtreecommitdiff
path: root/src/saffron_text.c
blob: 6e7accfc78a71ff878970c8ccd626917f38170db (plain)
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
#include <SDL3/SDL_render.h>
#include <saffron.h>
#include <SDL3/SDL.h>
#include <SDL3_ttf/SDL_ttf.h>
#include <stdlib.h>
#include <string.h>

static void saffron_text_free(SaffronWidget* self) {
	free(((SaffronText*)self)->text);
}

static void saffron_text_draw(SaffronWidget* widget, SDL_Renderer* renderer) {
	SaffronText* text = (SaffronText*)widget;
	if (!text->text || !text->font) return;

	SDL_Surface* surface = TTF_RenderText_Blended(text->font, text->text, 0, text->color);
	if (!surface) return;

	SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
	SDL_FRect dest = {widget->x, widget->y, (float)widget->w, (float)widget->h};
	SDL_RenderTexture(renderer, texture, NULL, &dest);

	SDL_DestroyTexture(texture);
	SDL_DestroySurface(surface);
}

SaffronText* saffron_text_new(const char* text, TTF_Font* font, SDL_Color color) {
	SaffronText* text_widget = malloc(sizeof(SaffronText));
	if (!text_widget) return NULL;

	saffron_widget_init((SaffronWidget*)text_widget);

	((SaffronWidget*)text_widget)->type = SAFFRON_WIDGET_TEXT;
	((SaffronWidget*)text_widget)->draw = saffron_text_draw;
	((SaffronWidget*)text_widget)->free = saffron_text_free;

	int w, h;
	if (!TTF_GetStringSize(font, text, 0, &w, &h)) {
		w = 0;
		h = 0;
	}
	((SaffronWidget*)text_widget)->w = w;
	((SaffronWidget*)text_widget)->h = h;

	text_widget->text = malloc(strlen(text) + 1);
	if (text_widget->text) {
		strcpy(text_widget->text, text);
	}
	text_widget->font = font;
	text_widget->color = color;

	return text_widget;
}