Text drawing function with SDL_ttf.

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
User avatar
Falco Girgis
Elysian Shadows Team
Elysian Shadows Team
Posts: 10294
Joined: Thu May 20, 2004 2:04 pm
Current Project: Elysian Shadows
Favorite Gaming Platforms: Dreamcast, SNES, NES
Programming Language of Choice: C/++
Location: Studio Vorbis, AL
Contact:

Text drawing function with SDL_ttf.

Post by Falco Girgis »

I made this function to use with the Null level editor. It works quite well and I hope you can use it also.

Code: Select all

#define C_ALIGN -1
#define R_ALIGN -2
#define L_ALIGN -3
#define B_ALIGN -2
#define T_ALIGN -3

void DrawText(char *text, int x, int y, Uint8 r, Uint8 g, Uint8 b) {
	SDL_Color color;
	color.r = r;
	color.g = g;
	color.b = b;

	SDL_Surface *g_pTextSurface = TTF_RenderText_Blended(g_Font, text, color);

	//rectangles
	SDL_Rect rcSrc;
	SDL_Rect rcDst;

	//source rectangle
	rcSrc.x = 0;
	rcSrc.y = 0;
	rcSrc.w = g_pTextSurface->w;
	rcSrc.h = g_pTextSurface->h;

	//destination rectangle
	rcDst = rcSrc;
	
	if(x == C_ALIGN) rcDst.x = (SCREEN_WIDTH-rcDst.w)/2;
	else if(x == R_ALIGN) rcDst.x = SCREEN_WIDTH - rcDst.w;
	else if(x == L_ALIGN) rcDst.x = 0;
	else rcDst.x = x;
	
	if(y == C_ALIGN) rcDst.y = (SCREEN_HEIGHT - rcDst.h)/2;
	else if(y == B_ALIGN) rcDst.y = SCREEN_HEIGHT - rcDst.h;
	else if(y == T_ALIGN) rcDst.y = 0;
	else rcDst.y = y;

	//blit the surface
	SDL_BlitSurface(g_pTextSurface, &rcSrc, g_pMainSurface, &rcDst);
}
It requires that you have g_pTextSurface and g_pMainSurface surfaces for the text to be blitted from and the MainSurface for it to be displayed on.

Parameter one is just a string with whatever you want it to print to the screen.

Then the x and y coordinates of where you want it (pass one of the #defined constants for auto-alignage).

Then you have your R, G, B.

The function takes care of the rest. Here is an example of a sample function call:

Code: Select all

DrawText("Null Level Editor: Beta Versionz0rz", C_ALIGN, 10, 0, 50, 255);
Enjoy.
User avatar
JS Lemming
Game Developer
Game Developer
Posts: 2383
Joined: Fri May 21, 2004 4:09 pm
Location: C:\CON\CON

Post by JS Lemming »

Koo dat.
Small girl at the harbor wrote:Look Brandon, that crab's got ham!
Post Reply