OK,
If I didn’t know how to output text in SDL and I asked on a list and got
the response this poor guy got, I’d be pretty bummed out…
so, if he’s still there, here’s a simplified version of some code I wrote
for a text widget…
It should be fairly straight forward to see what is going on…
You need SDL_ttf and FreeType installed to get this working, though there
are instructions on the places you download these libraries from…
(try libsdl.org)
NOTE, you should only call TTF_RenderText when you absolutely need to (ie
when the text changes, as TTF_RenderText is quite expensive…
This example will only call it once, if you plan to change the text in
this calass then you will need to add some way of letting Draw know it has
to re-render the text surface…
Hope this helps some…---------------
//---------------EText.h--------------------------------------------------------------------------------------------------------
class EText
{
public:
void SetText(char *text);
void SetColour(int r,int g,int b);
void SetFont(char *font, int size);
virtual void Draw(SDL_Surface *screen);
EText();
virtual ~EText();
protected:
TTF_Font *mFont;
SDL_Surface *mRenderedText;
SDL_Color mColour;
int mX;
int mY;
int mWidth;
int mHeight;
};
//---------------EText.c--------------------------------------------------------------------------------------------------------
void EText::Draw(SDL_Surface *screen)
{
SDL_Rect frect;
if(!mFont)
return;
if(!mRenderedText) {
mRenderedText = TTF_RenderText_Solid(mFont, mText, mColour));
}
if(mRenderedText) {
frect.x = mX;
frect.y = mY;
frect.w = mRenderedText->w;
frect.h = mRenderedText->h;
SDL_BlitSurface(mRenderedText, NULL, screen, &frect);
mWidth=mRenderedText->w;
mHeight=mRenderedText->h;
}
}
void EText::SetFont(char *font, int size)
{
if(mFont)
TTF_CloseFont(mFont);
mFont = TTF_OpenFont(font, size);
}
void EText::SetColour(int r, int g, int b)
{
mColour.r=r;
mColour.g=g;
mColour.b=b;
}
void EText::SetText(char *text)
{
if(!mText || sizeof(mText)<(strlen(text)+1))
mText=(char *)realloc(mText,(strlen(text)+1));
memset(mText,0,sizeof(mText));
strcpy(mText,text);
}
Yours,
Andy Gordon
QueriX UK
36A London Road http://www.querix.co.uk
Southampton
Tel: +44 23 8023 2345 andy at querix.co.uk
Fax: +44 23 8039 9685