Quellcode durchsuchen

Experiment with sdl and font drawing

It's... fun?  And frustrating.  But fun.  But frustrating.
Luna Stadler vor 4 Jahren
Ursprung
Commit
e10037996a
3 geänderte Dateien mit 88 neuen und 0 gelöschten Zeilen
  1. 2 0
      c/sdl/.gitignore
  2. 2 0
      c/sdl/Makefile
  3. 84 0
      c/sdl/hello_sdl.c

+ 2 - 0
c/sdl/.gitignore

@ -0,0 +1,2 @@
1
/hello_sdl
2
*.ttf

+ 2 - 0
c/sdl/Makefile

@ -0,0 +1,2 @@
1
hello_sdl: hello_sdl.c
2
	$(CC) $(pkg-config --cflags --libs sdl2 SDL2_ttf) hello_sdl.c -o hello_sdl

+ 84 - 0
c/sdl/hello_sdl.c

@ -0,0 +1,84 @@
1
#include <SDL.h>
2
#include <SDL_ttf.h>
3
4
char *font_file = "./FantasqueSansMono-Regular.ttf";
5
6
int main(int argc, char *argv[]) {
7
	printf("hello, world!\n");
8
9
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
10
		printf("shit: %s\n", SDL_GetError());
11
		return 1;
12
	}
13
14
	if (TTF_Init() != 0) {
15
		printf("ttf init: %s\n", TTF_GetError());
16
		return 1;
17
	}
18
19
	if (argc > 1) {
20
		font_file = argv[1];
21
	}
22
	printf("using font '%s'\n", font_file);
23
24
	TTF_Font *font = TTF_OpenFont(font_file, 20);
25
	if (font == NULL) {
26
		printf("open font: %s\n", TTF_GetError());
27
		return 1;
28
	}
29
30
	SDL_Window *window = SDL_CreateWindow("hello fonts", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 600, 100, SDL_WINDOW_BORDERLESS);
31
	if (window == NULL) {
32
		printf("create window: %s\n", SDL_GetError());
33
		return 1;
34
	}
35
36
	SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
37
	if (renderer == NULL) {
38
		printf("create renderer: %s\n", SDL_GetError());
39
		return 1;
40
	}
41
42
	char *msg = "howdy there, enby!🐘";
43
44
	// thanks to https://stackoverflow.com/questions/22886500/how-to-render-text-in-sdl2 for some actually useful code here
45
	SDL_Color white = {255, 255, 255};
46
	SDL_Color black = {0, 0, 0};
47
	SDL_Surface* surfaceMessage = TTF_RenderUTF8_Blended(font, msg, white); 
48
	SDL_Texture* message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);
49
50
	SDL_Rect text_rect;
51
	text_rect.x = 0;
52
	text_rect.y = 0;
53
	text_rect.w = surfaceMessage->w;
54
	text_rect.h = surfaceMessage->h;
55
56
	int advance = 0;
57
	for (int i = 0; i < strlen(msg); i++) {
58
		TTF_GlyphMetrics(font, msg[i], NULL, NULL, NULL, NULL, &advance);
59
		printf("advance '%c': %d\n", msg[i], advance);
60
	}
61
62
	SDL_Event event;
63
	while (1) {
64
		SDL_PollEvent(&event);
65
		if (event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) {
66
			printf("quit received\n");
67
			break;
68
		}
69
70
		SDL_RenderClear(renderer);
71
		SDL_RenderCopy(renderer, message, NULL, &text_rect);
72
		SDL_RenderPresent(renderer);
73
74
		SDL_Delay(16);
75
	}
76
77
	SDL_FreeSurface(surfaceMessage);
78
	SDL_DestroyTexture(message);
79
	SDL_DestroyWindow(window);
80
81
	SDL_Quit();
82
83
	printf("done here.\n");
84
}