SDL_ttf load font from memory

I have my own resource management system, I am trying to figure out how load a TTF_Font directly from memory instead of a file for using with SDL_ttf, I am a bit lost with it’s API, does anyone knows how to do this?

You can load font data from memory by doing it like this:

// Some font data as a stream of bytes
const char* pFontData[256];

const int FontSize = 16;

// Load the font data into a memory buffer
SDL_RWops* pFontMem = SDL_RWFromConstMem(pFontData, sizeof(pFontData));

if(!pFontMem)
{
	// Some error occurred while trying to read the data, act accordingly to that
}

// Load the font from the memory buffer
TTF_Font* pFont = TTF_OpenFontRW(pFontMem, 1, FontSize);

if(!pFont)
{
	// Some error occurred while trying to load the font, act accordingly to that
}
1 Like

Thanks!

SDL ttf creates a new SDL_Surface. I am trying to figure how to blit/blend this resulting surface to a R8G8B8A8 bitmap in memory now - it’s too soon into my experiment to look to switch to SDL surface in an entire codebase.

Is there any way? I found a blit but it also operates only on SDL surfaces. I also found the surface pixels but I don’t understand what pixel format is supposed to be out of SDL_ttf renders.

If I knew that SDL_ttf would always render in 32 bit or it had some way to specify the format I could try to pick the surface pixels and blend with my own functions…

Edit: Found some way but my texts have a black background instead of transparent. Everything else seems to work though…

So, I got it working, but I am trying to optimize things a bit now…

When I do the following, and pick the resulting surface, everything works

glyph = TTF_RenderText_Blended(font, text, sdlColor);
SDL_Surface * surface = SDL_CreateRGBSurfaceWithFormat(0, glyph->w,glyph->h, dest_depth, SDL_PIXELFORMAT_ARGB8888);
SDL_BlitSurface(glyph, nullptr, surface, nullptr);

But if I don’t do the above, and pick glyph directly to show in the screen, skiping the intermediate surface, I get the following

As far as I can tell, both should be SDL_PIXELFORMAT_ARGB8888, so any idea why the difference happens? (I am picking it’s pixels directly…)

I noticed one surface has pitch=416 and the other has pitch=344, I can’t figure other differences in formats… (looking in the debugger)

Wuhu, ok, learned what pitch is, now I can properly lookup the pixels!

So you don’t actually use SDL_Texture's in your code base to render images to the screen? I can see that you’re instead using the SDL_Surface directly and render it to the screen with SDL_BlitSurface().

I sadly don’t have much knowledge about the old pipeline anymore, i.e working with-, manipulating and rendering of an SDL_Surface, since I nowadays use SDL_Texture in combination with SDL_RenderCopy*.

But I’m glad you got it solved in the end.

1 Like