Dear ImGui, in short, for those who don’t know it yet, it creates immediate mode.
This means that you don’t create graphical interfaces from scratch with Dear ImGui. It uses a library that has graphical windows and overlays its widgets on that window to facilitate changes and configurations without having to leave the screen you are on.
To focus on implementing ImGui in SDL2, let’s reuse that basic code we used in this article from SDL2!
Let’s start!
Preparing the files
Clone and copy the necessary files.
Create a project:
Clone Dear ImGui:
Create a subfolder to organize the location of the files that will be included:
Copy all .h and .cpp from the root of the cloned Dear ImGui repository to your project:
Note: Download the image available in the other article
vim main.cpp:
Compile the code: g++ main.cpp $(pkg-config --cflags --libs sdl2) and run: ./a.out
To be able to move the Dear ImGui window in this specific example, let’s comment out the line that listens to the click event. To do this, comment leaving the lines like this:
Add the headers:
Initialize Dear ImGui
After initializing the Window (window) and the Renderer (renderer)
Add the SDL2 events for Dear ImGui inside the event loop:
Initialize Dear ImGui Frame:
Inside the loop after the events.
Create the Dear ImGui windows
Basic example only displays text similar to Hello World
Before the last SDL_RenderClear add the ImGui window display:
Release the resources used by Dear ImGui in conjunction with those used by SDL2
After the main loop at the end of the program execution.
Compiling
The files in the sdl2gui/ folder must be compiled separately with the -c parameter and saving as object: .o to only generate the Assembly code without being executed by the Linker. Only later link them to the binary that contains our main function.
Note the Makefile:
Check -I for some headers for Impl.
Then just run the make command, in this case the .o objects will be automatically deleted by the Makefile in addition to the code also being executed by the Makefile
Changing the SDL2 window background with Dear ImGui
Add this code:
Outside the main loop.
Add ImGui widget to change colors:
Change the Background Color of the SDL2 Window that has the line: SDL_SetRenderDrawColor(renderer, 9, 20, 33, 255); with the line below:
Multiplying by 255 is essential for the changes made by ImGui to take effect!