Go SDL2 Lesson 4
Working with fonts
July 1, 2016
While I was working on lesson 4 I noticed that the SDL2 bindings had been updated since the last time I checked, and the update added a new example on font rendering. Fortunately for me, the example doesn’t deal with hardware acceleration and only handles 1 of the 3 types of fonts so I’m not trashing this lesson.
It is worth remembering that the default for “go get” when pointed at a package is to add any files the local repository is missing and leave everything else alone. Use “go get -u” to also update local files. Lesson 4 source code (and font) is available on Github. The code is a bit different from the previous lessons, stuffing everything into a main() was getting to be a mess.
This lesson uses the SDL_tff library so a new import has been added.
Much like SDL2’s sdl.Init, to use SDL_tff you must first initialize it.
Opens the true type font file and sets the size of the font type.
These 3 functions all render text to a surface. When programming in C/C++ SDL provides numerous different ways to input text and turn it into a surface. With Go there is only the UTF-8 functions. Go is all about the UTF-8 - hardly surprising since the co-creators of UTF-8 (Rob Pike & Ken Thompson) make up two of the three original creators of Go.
Once the newly created surface with text is created the program turns it into a hardware accelerated texture.
Once the text has been turned into a texture it is just like lesson 3 and dealing with images. All that’s left is the clean up.
Release the surface memory since it is no longer needed. It would be nice to be able to skip the surface creation and go straight to a texture but that is not an option with the SDL_tff library.
When we no longer need the font *ttf.Font it is released from memory in the program.
Like any texture, once we are done using the texture with the text it needs to be properly released.
Time to properly shut down the SDL_tff library.
The glorious multicolored text program
So about those 3 types of text renderings (solid/shaded/blended)…. Typically it goes:
Sold: The best performance but lowest quality, best to use on text that frequently changes such as fps counters
Shaded: Gives nicer anti-aliased text but is slower than Solid and has a box around it
Blended: Best quality, slowest performance.
July 31, 2018 Update: Updated code to deal with breaking changes introduced to Go-SDL2 by version 0.3.