Development Environment: MacOS
Reference Link: Teacher Chen Yun's SDL2 Tutorial
Note: Study Notes
Drawing Text#
To draw text, we need to use a font library. My suggestion is to use Source Han Sans or De Yi Ti created by Bilibili user oooooohmygosh. Both fonts are open source and free to use.
We also need to download the SDL2_image library:
Use brew to download brew install sdl2_image
Then use brew info sdl2_image to check the location.
Finally, configure CMake as follows:
Open the font in the main function:
Don't forget to release it:
Then write a draw function to render the font:
Then just run it.
About Frame Rate Detection#
First, what is frame rate?
Frame rate is a measure used to indicate the number of frames being displayed per second. The unit of measurement is "frames per second" (FPS) or "hertz". Generally, FPS is used to describe how many frames are played per second in videos, electronic graphics, or games. -- Wikipedia
So it's quite simple to implement. We just need to know the time when the rendering starts and subtract the time when it ends to get the current frame rate.
Therefore, we need to set a value at the beginning of the program's main loop. SDL2 provides us with the SDL_GetTicks() function, which allows us to easily get the time when the program starts.
Then subtract the start time from the end time:
We can also lock the frame rate to maintain a stable value:
About the Viewport#
Setting the viewport allows us to conditionally limit the display of everything.
For example, if I want everything to be displayed in a 300*300 matrix with x=10, y=50, I can write it like this:
You will find that everything rendered with the renderer is now inside the destination box.