Elis Öhrman
Elis Öhrman

Reputation: 21

Draw Text to Screen

So I just want to point out that I am pretty new to code outside engines so this is somewhat new to me.

I am using SDL as a base for my game and would like to know a easy way to draw text, in the form of score/time, on the screen.

So far when searching I have not found anything that I've really understood or how to use. The thing I find most when searching with the tag SDL is SDL_ttf and I've tried to look into it but with no success.

So again, I am looking for an easy way to display text, string and float/int, in the form of score/time.

Upvotes: 1

Views: 3790

Answers (2)

DanBennett
DanBennett

Reputation: 448

you'll want the SDL ttf library - it handles truetype fonts relatively straightforwardly.

http://www.libsdl.org/projects/SDL_ttf/ and documentation http://jcatki.no-ip.org:8080/SDL_ttf/ http://jcatki.no-ip.org:8080/SDL_ttf/SDL_ttf.html

see especially documentation for TTF_OpenFont, TTF_CloseFont (to open & close a font file) and the rendering functions eg TTF_RenderText_Solid

In your position I'd probably write a couple of helper functions to handle drawing text that wraps these, passing on the string, location to draw etc. and call them whenever you need to print score/etc.

Upvotes: 0

Zereges
Zereges

Reputation: 5209

Library SDL alone do not have support for writing text to the screen. Your search leads to SDL_ttf, which is right library to use.

Example of usage (only extra code, supposing you already called SDL_Init, created SDL_Window and you have SDL_Renderer* renderer for that window.

const SDL_Rect* dstrect;
SDL_Color color;

TTF_Init();
TTF_Font* font = TTF_OpenFont("font.ttf" /*path*/, 15 /*size*/);
SDL_Surface* textSurface = TTF_RenderText_Blended(font, "Text to render", color);

SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
SDL_RenderCopy(renderer, textTexture, NULL, dstrect);

SDL_FreeSurface(textSurface);
SDL_DestroyTexture(textTexture);
TTF_CloseFont(font);
TTF_Quit();

Look into docs for other TTF_RenderText_* methods and how they differ.

And since you are using C++ (both SDL and SDL_ttf is in C), you probably want to write some wrappers around TTF rendering.

Upvotes: 2

Related Questions