7

Here are the facts: I am using codeblocks on Ubuntu. I have installed SDL and SDL_ttf and have included and linked them successfully. I want to render text to the screen of the font, FreeSerif.

Here is the problem: When the program gets to the line, TTF_OpenFont("FreeSerif.ttf,20"), it returns NULL, which would then cause a segfault if passed to the TTF_RenderText_Solid function. I have added the font file to the project and it still did not work.

Here is the code:
TTF_Init();

TTF_Font *font = TTF_OpenFont("FreeSerif.ttf",20); //This returns NULL 

if(!font){printf("Unable to open font");exit(1);} //The program exits here
Martin Delille
  • 11,360
  • 15
  • 65
  • 132
biscuit
  • 85
  • 1
  • 1
  • 6

3 Answers3

11

I've had the same problem and it seems to be a path error, TTF_GetError() throw this :

Couldn't open Arial.ttf

You should set your font with absolute path and not a relative one. For me, it was

/Library/Fonts/Arial.ttf

instead of :

Arial.ttf

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
  • Also, it may be copied in the current directory of the executable. – Dmytro Sirenko May 07 '13 at 09:53
  • Sure, but depending on codeblocks (that I don't like at all but that's not the point) settings, the directory of the executable could be hard to determinate, that's why I think that an absolute path may help in diagnostic – Thomas Ayoub May 07 '13 at 09:59
4

You must specify the full path name. That, or you must be certain sure that the file is in the current directory for your program (which is not the same as the executable's directory).

So use this instead:

TTF_Font *font = TTF_OpenFont("/path/to/FreeSerif.ttf",20);
sashoalm
  • 75,001
  • 122
  • 434
  • 781
3
// load font.ttf at size 20 into font

TTF_Font *font;

font=TTF_OpenFont("font.ttf", 20);

if(!font) {
    printf("TTF_OpenFont: %s\n", TTF_GetError());
   // handle error
}

font.ttf path not found it return NULL value

if(!font) not check null value and TTF_GetError() It returns the last error.

Zizouz212
  • 4,908
  • 5
  • 42
  • 66
kunalg
  • 1,570
  • 1
  • 12
  • 18