I was wondering how to render text with SDL2. I found an API called SDL_TTF
and some tutorials, however they do not work with my situation.
I'm using an SDL_Window
and SDL_Renderer
, whereas the tutorials are specific to SDL_Surface
.
Is it possible to use SDL_TTF
with SDL_Render/SDL_Window
? If so, how?
SDL_ttf minimal runnable example
Not super efficient, but easy to integrate. For efficiency see: How to render fonts and text with SDL2 efficiently?
Kept in a separate repo than the main SDL source, but hosted on the same official server, so should be fine: http://hg.libsdl.org/SDL_ttf/
Newlines won't work. You have to work with line heights.
Compile and run:
You must pass the path of a TTF font file to the program.
ttf.c
GitHub upstream.
Tested in Ubuntu 16.04, SDL 2.0.4.
Yes it is. You create a surface with the text you want and then convert it to a texture that you can render.
Some sample code from one of my projects:
This assumes you've properly initialized SDL_ttf and loaded a font. In the example
score
is an int. The screen gets cleared and rendered to somewhere else (I didn't include that part).For a full working example, check out the tutorial for SDL_ttf in SDL2 at Lazy Foo.
Yep, it is possible, given that you have a renderer and a window plus you don't really have any thoughts on dabbling with surfaces then you might want to mind on creating texture, here is a sample code
I tried to explain the code line by line, you don't see any window right there since I already assumed that you knew how to initialize a renderer which would give me an idea that you also know how to initialize a window, then all you need is the idea on how to initialize a texture.
Minor questions here, did your window open? was it colored black? if so then my thoughts were right, if not, then you can just ask me and I could change this code to implement the whole section which consists of a renderer and a window.