Skip to content

Source: ImGui load and display a custom font

Lukas Dürrenberger edited this page Jun 3, 2022 · 1 revision

Displaying a custom font with ImGui can be a bit tricky, as a function specific for SFML needs to be called. I got a little headache figuring that out and with the help of "Big Blue Bambo" from the SFML Discord Server I got it right. Maybe it helps you out as well.

So let's get into it!

#include <SFML\Graphics.hpp>

#include "imgui\imgui.h"
#include "imgui\imgui-SFML.h"

int main()
{
	sf::RenderWindow window(sf::VideoMode(512, 512), "imGui with custom Font!");

	ImGui::SFML::Init(window);
	//Lets get rid of the ini file
	ImGui::GetIO().IniFilename = nullptr;

	//Add the fonts (remember to fill in the correct path of your font
	ImGui::GetIO().Fonts->AddFontFromFileTTF("data/fonts/kenney space.ttf", 18);

	//This function is important else the program will crash with an assertion
	ImGui::SFML::UpdateFontTexture();

	sf::Clock clock;
	
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			ImGui::SFML::ProcessEvent(event);

			if (event.type == sf::Event::Closed)
				window.close();
		}

		ImGui::SFML::Update(window, clock.restart());

		//As the default font is also loaded we need to push the newly loaded one.
		ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]);
		ImGui::Begin("Hello, world!");
		ImGui::Button("Look at this pretty button");
		ImGui::End();
		ImGui::PopFont();

		window.clear();

		ImGui::SFML::Render(window);

		window.display();
	}

	ImGui::SFML::Shutdown();

	return 0;
}
Clone this wiki locally