TTF_OpenFont() returns NULL
Asked Answered
E

4

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
Eldredge answered 26/12, 2012 at 16:41 Comment(2)
I am having the same problem but I am using Qt Creator on MacOSX.Frulla
Did you try TTF_GetError()? It may say more about the opening error.Laodicean
I
12

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

Illhumored answered 7/5, 2013 at 9:52 Comment(2)
Also, it may be copied in the current directory of the executable.Laodicean
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 diagnosticIllhumored
P
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);
Panter answered 10/5, 2013 at 8:20 Comment(0)
K
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.

Kieffer answered 8/5, 2013 at 13:30 Comment(0)
T
0

I'm using Xcode 15.2 and I encountered this problem, and I encountered this problem and spent a whole day figuring out what's wrong. I've tried the absolute path, relative path, reinstalling SDL and just about everything I thought of, and then I went to the build phases, copy bundle resources and add the font file there for everyone who encounters the same problem.

Tankard answered 10/2 at 12:43 Comment(1)
Thanks for your contribution, but try to keep your answer to the point, i.e. explain how you solved the problem (and not how much time you have spent and/or all the tried solutions that don't work).Gailey

© 2022 - 2024 — McMap. All rights reserved.