tomato-testing/docs/FONTS.md
Green Sky 5dd9834009 Squashed 'external/imgui/imgui/' changes from d6cb3c923d2..b475309fa1e
b475309fa1e Fonts: Fixed font ascent and descent calculation when a font hits exact integer values. (#7399, #7404)
daecfffefbc Text, DrawList: Improved handling of long single-line wrapped text. (#7496, #5720)
fab96a6e593 Backends: SDL3: Re-enable calling SDL_StartTextInput()/SDL_StopTextInput(). (#7452, #6306, #6071, #1953)
dad1689bf7b Examples: SDL3: amend for removal of SDL_RENDERER_ACCELERATED.
3caa79c8a53 Version 1.90.6 WIP
76bc1b825e6 Extracted part of NewFrame() into SetupDrawListSharedData() for documentation purpose. (#7495, #6406)
f790d516652 Silent zealous/stupid warning introduced by Clang 16 (shipping with VS2022) with -Weverything. Pointers are now illegal!
231cbee0fc4 Version 1.90.5
4f9ba19e520 Drags, Sliders, Inputs: Reactivated decimal point replacement for SliderScalar and DragScalar. (#7389, #6719, #2278)
e7712ff103d Out of courtesy/consistency move all the DebugHookIdInfo compares into ifndef block.
f959c417fec Refactor moving ID stack functions to their own section (part 2)
0bf134a8e2e Refactor moving ID stack functions to their own section.
9a2b598ec1e ListBox: Fixed text-baseline offset when using SameLine()+Text() after a labeled ListBox().
d3c3514a59b Tables: Fixed auto-width columns when using synced-instances of same table. (#7218)
25a492f3307 ProgressBar: Fixed passing fraction==NaN from leading to a crash. (#7451)
9638c2839a1 Internals: adding ImGuiNavMoveFlags_NoClearActiveId even though there's currently no satisfying way to take advantage of it. (#1418)
742e53434f4 Child Windows: adjust resizing limits to match window padding rather than inner clipping rectangle. (#7440)
515b437c084 Child windows: look at the parent window's flags to decide whether to clamp child resizes. (#7440, #1710)
976dc239656 Windows: extend outer resize borders to the edges when there are no corner grips. (#7440, #1710)
37b37fc2a3e DrawList: Allow AddText() to accept null ranges. (#3615, 7391)
5c5ae806aa1 Comments
cf4c10bef74 Style: added ImGuiStyleVar_TabBorderSize, ImGuiStyleVar_TableAngledHeadersAngle. (#7411)
f0802287db5 Tables: Angled headers: fixed table contents overflowing when a list clipper is used. (#7416)
29ff159f941 Tables: Angled headers: fixed borders not moving back up after TableAngleHeadersRow stops being called. (#7416)
38ddfb24f09 Tables: Angled headers: fixed border hit box extending beyond non-scrollable tables. (#7416)
8be48a44f78 Backends: WebGPU: Avoid using -1u literal (#7436)
868facff9de ImDrawList: (Breaking) merge float radius_x/radius_y parameters into ImVec2 radius in PathEllipticalArcTo(), AddEllipse(), AddEllipseFilled(). (#2743, #7417)
0a1f5b94e31 Demo: Two minor fixes (unchecked BeginTooltip + incorrect height constraint) (#7410)l
40df3db1a2a Tweaking terminology
da29b776eed Backends: SDL3: Fix leak of SDL_GetGamepads() return value (#7381)
3c435c02978 Inputs: (Breaking) More formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. (#4921)
286cd5bd41e Internals, InputText: removed ImGuiInputSource_Clipboard. (#4005)
fc570ac9225 Examples: WGPU: fixed initialization of WGPURenderPassColorAttachment (#7371)
65dc67f63c6 Windows: Double-click to collapse may be disabled via key-ownership mechanism. (#7369)
6b7358e9f36 InputText: adding clarifying note about ImGuiInputTextCallbackData::Buf. (#7363)
fbf45ad149b ImDrawList: add PathFillConcave(), AddConcavePolyFilled(): amends (#760)
1ff90c52d5f ImDrawList: add PathFillConcave(), AddConcavePolyFilled() (#760)
04f40014a62 Docs: added a mini wiki index in main source files.
c6236699671 Added link to crawlable wiki
0573513d6df Windows: Scrollbar visibility decision uses current size when both size and contents size are submitted by API. (#7252)
44c7dfca030 Menus, Popup: Amend c3f8f4d for static analyzer warning ("condition always true"). (#7325)
c3f8f4de257 Menus, Popups: Fixed an issue where sibling menu popups re-opening in successive frames would erroneously close the window. (#7325, #7287, #7063)
98779417751 Popups, Menus: rename ImGuiPopupData::BackupNavWindow > RestoreNavWindow and minor tweaks. Should be functionally a no-op.
725f91922d5 Tables: fixed TableGetHoveredRow() with overlapping frozen rows (#7350, #6588, #6347, #6250)
e46d1e69ac3 Version 1.90.5 WIP
277ae93c413 Version 1.90.4
f5be90523d6 Nav: Fixed SetKeyboardFocusHere() or programmatic tabbing API from not working on windows with the ImGuiWindowFlags_NoNavInputs flag.
13d91ff9188 Nav: Fixed SetKeyboardFocusHere() or programmatic tabbing API from not working on windows with the ImGuiWindowFlags_NoNavInputs flag.
34965cf23a7 Modals: Temporary changes of ImGuiCol_ModalWindowDimBg are properly handled by BeginPopupModal(). (#7340)
659fb41d0a2 Debug Tools: moved DebugStartItemPicker() to public API. Added to Demo->Tools menu. (#2673)
198c38f0b11 Demo: Custom Rendering: better demonstrate PathArcTo(), PathBezierQuadraticCurveTo(), PathBezierCubicCurveTo(), PathStroke(), PathFillConvex() functions.
3b6d924acd0 ProgressBar: Fixed a minor tesselation issue when rendering rounded progress bars.
d3f1a7165cb Popups: allow Child Popups to be resizable if not explicitly disabling.
e78ce72eb6d Popups: Fixed resizable popup minimum size being too small. Standardized CalcWindowMinSize() logic a bit more. (#73290
014e0ac8c92 Menus, Popups: Fixed an issue where hovering a parent-menu upward would erroneously close the window. (#7325, #7287, #7063)
c16043c1d58 Tables: Angled headers: improve clipping of text since multi-line labels makes clipping issues visible. (#6917)
405e54ebd50 Tables: Angled Headers: fixed support for multi-line labels. various padding/layout fixes. (#6917)
6655ab2e43f Tables: Angled Headers: fixed TableAngledHeadersRow() incorrect background fill drawn too low. Fixed row geometry with non-small values of CellPadding. (#6917)
9159cd7b4ac Updated invalid documentation link (#7331)
ccc5347e451 Fix typos (#7332)
8a14b71f228 Version 1.90.4 WIP
b19a4c5f2b3 Backends: OSX: remove legacy clearing of io.NavInputs in ImGui_ImplOSX_UpdateGamepads(). (#7320)
5b6f03213dd Version 1.90.3
f80e65a4068 Backends:,Examples: Vulkan: moved RenderPass parameter from ImGui_ImplVulkan_Init() function to ImGui_ImplVulkan_InitInfo structure. (#7308)
829f45df994 Backends: SDL2: removed obsolete ImGui_ImplSDL2_NewFrame(SDL_Window*) signature which was obsoleted in 1.84..
3cc37170ca7 Examples: GLFW+Metal: Add -I and -L paths for MacPorts.
891b81fc5d7 Backends: SDL3: Fixed gamepad. Added support for disconnection. Added support for multiple gamepads. Added ImGui_ImplSDL3_SetGamepadMode(). (#7180, #3884, #6559, #6890)
262e30e3001 Backends: SDL2: rework new API as ImGui_ImplSDL2_SetGamepadMode(). (#3884, #6559, #6890, #7180)
9dfa2397deb Internals: Fixed ImFileOpen not working before context is created. (#7314, #7315)
d15e4100b83 Backends: SDL2: Amend new API, all support for multiple gamepads. (#3884, #6559, #6890)
f966da1f8fb Backends: SDL2: Gamepad handlng: amend bf1c96d. (#3884, #6559, #6890)
bf1c96d4fa2 Backends: SDL2: Handle gamepad disconnection + fixed increasing refcount. Added  ImGui_ImplSDL2_SelectGamepadAuto()/ImGui_ImplSDL2_SelectGamepadExplicit(). (#3884, #6559, #6890)
fd8d6dc5d19 Backends: SDL2,SDL3: tidying up.
e0ba0d0433a Backends: Vulkan: Fixes for building with pre Vulkan 1.3. Amend 8901931. (#7166)
11d73f03ee5 Backends: Vulkan: Fix/amend 8901931
89019319ddb Backends: Vulkan: use PipelineRenderingCreateInfo for dynamic rendering (#7166, #6855, #5446, #5037)
1d6f0cea0e6 Backends: DX9: use RGBA texture to avoid conversion if supported
3af739a2d17 Menus, Popups: fixed menus and popups with child window flag erroneously not displaying a scrollbar when contents is over parent viewport size. (#7287, #7063)
2af01baffd1 Backends: SDLRenderer3: query newly added SDL_RenderViewportSet() to not restore a wrong viewport if none was initially set.
915c6393ad7 Version 1.90.3 WIP
536090303a8 Version 1.90.2
7b5357d817e Debug Tools: Metrics: Improved Monitors and Viewports minimap display. Highlight on hover.
70aa717a8e1 Combo: Fixed not reusing windows optimally when used inside a popup stack.
5cdc4a2a413 Demo: use ImGui::MemAlloc/MemFree for consistency. (#7300)
76e09c4b0fa ClosePopupsOverWindow(): amend to remove _ChildWindow test.
3a078466a7a Nav: ImGuiWindowFlags_NoNavInputs is tested during scoring so NavFlattened windows can use it.
7d67623d15b InputText: Internal: ReloadUserBufXXX functions don't override revert value. (#2890) fix accidental comment.
a5e0e90c16a Nav: tweak RenderNavHighlight() syntax. ImGuiNavHighlightFlags_TypeThin -> ImGuiNavHighlightFlags_Compact.
1e8fc01ddd7 InputText: Internal: ReloadUserBufXXX functions don't override revert value. (#2890) + rename
a06dd7a27b6 OpenPopup(): Added ImGuiPopupFlags_NoReopen. Nav, Menus: Fixed click on a BeginMenu() followed by right-arrow. (#1497, #1533)
f104967c68f Comments
06ce312745e InputText: Internal: added reload from user-buf feature. (#2890)
f50ddc431e3 Fixed some typos. (#7282)
6172c22c5dc CI: Update to `actions/checkout` `v4` from `v3`. (#7281)
96839b445e3 Nav: Improve handling of Alt key to toggle menu so that key ownership may be claimed on indiviudal left/right alt key without intefering with the other.
71947563709 Shortcut: fixed single mod-key Shortcut from working e.g. Shortcut(ImGuiKey_LeftCtrl)
f1960b60c1a Added "nop" to IM_DEBUG_BREAK macro on GCC to work around GDB bug (#7266)
8491cf36adb Inputs: g.ActiveIdUsingManyKeys[] prevent routes from being claimed.
9176eedf240 Internals: SetShortcutRouting() move code so next commit is easier to read. Should be no-op.
1509842107d Backends: OpenGL3: Shallow tweak of compile-time extensions detection.
1ce41f6218d Backends: OpenGL3: Backup and restore GL_PIXEL_UNPACK_BUFFER. (#7253)
81e0be856a6 Fixed strict-aliasing violation in FormatTextureIDForDebugDisplay(). (#7090, #7256)
a201af73544 Added SetNextItemShortcut() wip function. (#456)
4c2c09450a6 Nav: keyboard/gamepad activation feedback properly timed instead of frame buffer. (#456)
5b5e9bd0cb3 Internals: Tweak shallow compaction as Clang complains about MS ABI signage of enums.
7c3fa7d049a Refactor: moved section in imgui_internal.h
9266c0d2d13 Backends: WebGPU: Avoid leaking pipeline layout. (#7245)
595eb86624d Changelog, comment, minor data compaction
6850194f60a CI: Fixes WGPU example build.
5fc0a361b24 Backends: WebGPU: added ImGui_ImplWGPU_InitInfo::PipelineMultisampleState. (#7240)
831d42c1ab3 Backends: WebGPU: ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes. (#7240)
e3c7ff944d5 Examples: Emscripten+WebGPU: slightly refactor like other Emscripten compatible Desktop examples, as aiming to make this suppot desktop eventually.
15908502ed6 Backends: Vulkan: Define NOMINMAX when VK_USE_PLATFORM_WIN32_KHR is defined. (#7250)
788747f8635 Examples: Emscripten+WebGPU: Remove use of deprecated ObjectBase<...>::Release in favor of ::MoveToCHandle (#7251)
763100b3858 Nav: Fixed pressing Escape while in a child window with _NavFlattened flag. (#7237)
c7edb446caa Shortcut(): always test ownership.
1844f903d55 Nav: space/enter poll check ownership. InputText: declare ownership of Enter key as it doesn't go through Shortcut
5ddfbb80d86 Backends: Vulkan: Fixed vkAcquireNextImageKHR() validation errors in VulkanSDK 1.3.275 by allocating one extra semaphore than in-flight frames. (#7236)
2f483373355 Examples: Vulkan: Rename compile-time defies for the examples to remove misleading IMGUI_ prefixes.
d7c2a0e38f4 Shortcut(): fixed 8323a06 adding _Repeat to all Shortcut() calls.
3b828d3701e Refactor: moving ItemAdd() into a section abote ItemSize(). No logic change (part 2)
ff5f3aa38b5 Refactor: moving ItemAdd() into a section abote ItemSize(). No logic change (part 1)
1a48a634466 Enclosed a few more remaining sections in ifndef IMGUI_DISABLE_DEBUG_TOOLS for completeness.
33fabdf392d Scrollbar() doesn't forcefully mark itself as hovered when held.
d431d85839b Internals: removed obsolete ImPool::GetSize() (last used by implot 0.10, changed in implot 0.11)
f0d1f61fa51 Internals: commented out long-time obsoleted FocusableItemRegister()/FocusableItemUnregister() documentaton-only leftovers. +
095665977f6 Nav: marking NavId as hovered in ButtonBehavior() doesn't check for ActiveId.
d10641b04a3 Nav: keyboard/gamepad activation mark widgets as held to give better visual feedback.
03417cc77d1 Backends: WebGPU: Filling all WGPUDepthStencilState fields explicitly as a recent Dawn update stopped setting default values. (#7232)
5fdcdf7080a Shortcut: ImGuiInputFlags_RouteFocused policy can filter Shortcuts conflicting with character input when an item is active. (#456)
80d5cb1ab1f Comments around ImGuiInputFlags.
1cc0eb4d322 Internals: Rename NavFocusScopePath to NavFocusRoute + fixed a static analyzer warning.
46e5f44ec8c Shortcut()/SetShortcutRouting(): use mixed current window focus scope + ParentWindowForFocusRoute. (#6798, #2637, #456)
e0c8c80adaa Shortcut()/SetShortcutRouting(): focus route testing now use ParentWindowForFocusRoute. Automatically set on child-window, manually configurable otherwise. (#6798, #2637, #456)
4b20a0217eb Internals: add window to FocusScopeStack. (#6798)
2156db7a075 Debug Log: added InputRouting logging. Made GetKeyChordName() use its own buffer. Fixed debug break in SetShortcutRouting(). (#6798, #2637, #456)
dd0efdc6371 Fixed SetKeyboardFocusHere() not working when current nav focus is in different scope. (#7226)
8a3dfda8d08 Commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
6228c2e1ec7 Backends: Vulkan: moved ImGui_ImplVulkanH_DestroyFrameRenderBuffers/ImGui_ImplVulkanH_DestroyWindowRenderBuffers as they are always used in a state where backend data is available.
70bb6d1e790 Backends: Vulkan: Fixed vkMapMemory() calls unnecessarily using full buffer size. (#3957)
82df7c8bf41 Backends: Vulkan: Fixed handling of ImGui_ImplVulkan_InitInfo::MinAllocationSize field. (#7189, #4238)
29809d72202 Version 1.90.2 WIP
db049db8608 Docs: tweak, fixed misplaced changelog entry. (#7084)

git-subtree-dir: external/imgui/imgui
git-subtree-split: b475309fa1e9d7a91825a169e243f9c4fa085f71
2024-04-15 18:19:01 +02:00

24 KiB

(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/FONTS.md or view this file with any Markdown viewer)

Dear ImGui: Using Fonts

The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer), a 13 pixels high, pixel-perfect font used by default. We embed it in the source code so you can use Dear ImGui without any file system access. ProggyClean does not scale smoothly, therefore it is recommended that you load your own file when using Dear ImGui in an application aiming to look nice and wanting to support multiple resolutions.

You may also load external .TTF/.OTF files. In the misc/fonts/ folder you can find a few suggested fonts, provided as a convenience.

Also read the FAQ: https://www.dearimgui.com/faq (there is a Fonts section!)

Index


Troubleshooting

A vast majority of font and text related issues encountered comes from 4 things:

(1) Invalid filename due to use of \ or unexpected working directory.

See About Filenames. AddFontXXX functions should assert if the filename is incorrect.

(2) Invalid UTF-8 encoding of your non-ASCII strings.

See About UTF-8 Encoding. Use the encoding viewer to confirm encoding of string literal in your source code is correct.

(3) Missing glyph ranges.

You need to load a font with explicit glyph ranges if you want to use non-ASCII characters. See Fonts Loading Instructions. Use Debug Tools confirm loaded fonts and loaded glyph ranges.

This is a current constraint of Dear ImGui (which we will lift in the future): when loading a font you need to specify which characters glyphs to load. All loaded fonts glyphs are rendered into a single texture atlas ahead of time. Calling either of io.Fonts->GetTexDataAsAlpha8(), io.Fonts->GetTexDataAsRGBA32() or io.Fonts->Build() will build the atlas. This is generally called by the Renderer backend, e.g. ImGui_ImplDX11_NewFrame() calls it. If you use custom glyphs ranges, make sure the array is persistent and available during the calls to GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build().

(4) Font atlas texture fails to upload to GPU.

This is often of byproduct of point 3. If you have large number of glyphs or multiple fonts, the texture may become too big for your graphics API. The typical result of failing to upload a texture is if every glyph or everything appears as empty black or white rectangle. Mind the fact that some graphics drivers have texture size limitation. If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours.

Some solutions:

  • You may reduce oversampling, e.g. font_config.OversampleH = 1, this will half your texture size for a quality loss. Note that while OversampleH = 2 looks visibly very close to 3 in most situations, with OversampleH = 1 the quality drop will be noticeable. Read about oversampling here.
  • Reduce glyphs ranges by calculating them from source localization data. You can use the ImFontGlyphRangesBuilder for this purpose and rebuilding your atlas between frames when new characters are needed. This will be the biggest win!
  • Set io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight; to disable rounding the texture height to the next power of two.
  • Set io.Fonts.TexDesiredWidth to specify a texture width to reduce maximum texture height (see comment in ImFontAtlas::Build() function).
Return to Index

How should I handle DPI in my application?

See FAQ entry.

Return to Index

Fonts Loading Instructions

Load default font:

ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontDefault();

Load .TTF/.OTF file with:

ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);

If you get an assert stating "Could not load font file!", your font filename is likely incorrect. Read About filenames carefully.

Load multiple fonts:

// Init
ImGuiIO& io = ImGui::GetIO();
ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels);

In your application loop, select which font to use:

ImGui::Text("Hello"); // use the default font (which is the first loaded font)
ImGui::PushFont(font2);
ImGui::Text("Hello with another font");
ImGui::PopFont();

For advanced options create a ImFontConfig structure and pass it to the AddFont() function (it will be copied internally):

ImFontConfig config;
config.OversampleH = 2;
config.OversampleV = 1;
config.GlyphExtraSpacing.x = 1.0f;
ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config);

Combine multiple fonts into one:

// Load a first font
ImFont* font = io.Fonts->AddFontDefault();

// Add character ranges and merge into the previous font
// The ranges array is not copied by the AddFont* functions and is used lazily
// so ensure it is available at the time of building or calling GetTexDataAsRGBA32().
static const ImWchar icons_ranges[] = { 0xf000, 0xf3ff, 0 }; // Will not be copied by AddFont* so keep in scope.
ImFontConfig config;
config.MergeMode = true;
io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 18.0f, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge into first font
io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges);             // Merge into first font
io.Fonts->Build();

Add a fourth parameter to bake specific font ranges only:

// Basic Latin, Extended Latin
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, nullptr, io.Fonts->GetGlyphRangesDefault());

// Default + Selection of 2500 Ideographs used by Simplified Chinese
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, nullptr, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());

// Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, nullptr, io.Fonts->GetGlyphRangesJapanese());

See Using Custom Glyph Ranges section to create your own ranges.

Example loading and using a Japanese font:

ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
ImGui::Text(u8"こんにちは!テスト %d", 123);
if (ImGui::Button(u8"ロード"))
{
    // do stuff
}
ImGui::InputText("string", buf, IM_ARRAYSIZE(buf));
ImGui::SliderFloat("float", &f, 0.0f, 1.0f);

sample code output
(settings: Dark style (left), Light style (right) / Font: NotoSansCJKjp-Medium, 20px / Rounding: 5)

Return to Index

Loading Font Data from Memory

ImFont* font = io.Fonts->AddFontFromMemoryTTF(data, data_size, size_pixels, ...);

IMPORTANT: AddFontFromMemoryTTF() by default transfer ownership of the data buffer to the font atlas, which will attempt to free it on destruction. This was to avoid an unnecessary copy, and is perhaps not a good API (a future version will redesign it). If you want to keep ownership of the data and free it yourself, you need to clear the FontDataOwnedByAtlas field:

ImFontConfig font_cfg;
font_cfg.FontDataOwnedByAtlas = false;
ImFont* font = io.Fonts->AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg);
Return to Index

Loading Font Data Embedded In Source Code

  • Compile and use binary_to_compressed_c.cpp to create a compressed C style array that you can embed in source code.
  • See the documentation in binary_to_compressed_c.cpp for instructions on how to use the tool.
  • You may find a precompiled version binary_to_compressed_c.exe for Windows inside the demo binaries package (see README).
  • The tool can optionally output Base85 encoding to reduce the size of source code but the read-only arrays in the actual binary will be about 20% bigger.

Then load the font with:

ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...);

or

ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...);
Return to Index

Using Icon Fonts

Using an icon font (such as FontAwesome or OpenFontIcons) is an easy and practical way to use icons in your Dear ImGui application. A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without having to change fonts back and forth.

To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut: https://github.com/juliettef/IconFontCppHeaders.

So you can use ICON_FA_SEARCH as a string that will render as a "Search" icon.

Example Setup:

// Merge icons into default tool font
#include "IconsFontAwesome.h"
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontDefault();

ImFontConfig config;
config.MergeMode = true;
config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced
static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges);

Example Usage:

// Usage, e.g.
ImGui::Text("%s among %d items", ICON_FA_SEARCH, count);
ImGui::Button(ICON_FA_SEARCH " Search");
// C string _literals_ can be concatenated at compilation time, e.g. "hello" " world"
// ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB"

See Links below for other icons fonts and related tools.

Monospace Icons?

To make your icon look more monospace and facilitate alignment, you may want to set the ImFontConfig::GlyphMinAdvanceX value when loading an icon font.

Screenshot

Here's an application using icons ("Avoyd", https://www.avoyd.com): avoyd

Return to Index

Using FreeType Rasterizer (imgui_freetype)

  • Dear ImGui uses imstb_truetype.h to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read.
  • There is an implementation of the ImFontAtlas builder using FreeType that you can use in the misc/freetype/ folder.
  • FreeType supports auto-hinting which tends to improve the readability of small fonts.
  • Read documentation in the misc/freetype/ folder.
  • Correct sRGB space blending will have an important effect on your font rendering quality.
Return to Index

Using Colorful Glyphs/Emojis

  • Rendering of colored emojis is supported by imgui_freetype with FreeType 2.10+.
  • You will need to load fonts with the ImGuiFreeTypeBuilderFlags_LoadColor flag.
  • Emojis are frequently encoded in upper Unicode layers (character codes >0x10000) and will need dear imgui compiled with IMGUI_USE_WCHAR32.
  • Not all types of color fonts are supported by FreeType at the moment.
  • Stateful Unicode features such as skin tone modifiers are not supported by the text renderer.

colored glyphs

io.Fonts->AddFontFromFileTTF("../../../imgui_dev/data/fonts/NotoSans-Regular.ttf", 16.0f);
static ImWchar ranges[] = { 0x1, 0x1FFFF, 0 };
static ImFontConfig cfg;
cfg.OversampleH = cfg.OversampleV = 1;
cfg.MergeMode = true;
cfg.FontBuilderFlags |= ImGuiFreeTypeBuilderFlags_LoadColor;
io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\seguiemj.ttf", 16.0f, &cfg, ranges);
Return to Index

Using Custom Glyph Ranges

You can use the ImFontGlyphRangesBuilder helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs.

ImVector<ImWchar> ranges;
ImFontGlyphRangesBuilder builder;
builder.AddText("Hello world");                        // Add a string (here "Hello world" contains 7 unique characters)
builder.AddChar(0x7262);                               // Add a specific character
builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
builder.BuildRanges(&ranges);                          // Build the final result (ordered ranges with all the unique characters submitted)

io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, nullptr, ranges.Data);
io.Fonts->Build();                                     // Build the atlas while 'ranges' is still in scope and not deleted.
Return to Index

Using Custom Colorful Icons

As an alternative to rendering colorful glyphs using imgui_freetype with ImGuiFreeTypeBuilderFlags_LoadColor, you may allocate your own space in the texture atlas and write yourself into it. (This is a BETA api, use if you are familiar with dear imgui and with your rendering backend)

  • You can use the ImFontAtlas::AddCustomRect() and ImFontAtlas::AddCustomRectFontGlyph() api to register rectangles that will be packed into the font atlas texture. Register them before building the atlas, then call Build()`.
  • You can then use ImFontAtlas::GetCustomRectByIndex(int) to query the position/size of your rectangle within the texture, and blit/copy any graphics data of your choice into those rectangles.
  • This API is beta because it is likely to change in order to support multi-dpi (multiple viewports on multiple monitors with varying DPI scale).

Pseudo-code:

// Add font, then register two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font
ImFont* font = io.Fonts->AddFontDefault();
int rect_ids[2];
rect_ids[0] = io.Fonts->AddCustomRectFontGlyph(font, 'a', 13, 13, 13+1);
rect_ids[1] = io.Fonts->AddCustomRectFontGlyph(font, 'b', 13, 13, 13+1);

// Build atlas
io.Fonts->Build();

// Retrieve texture in RGBA format
unsigned char* tex_pixels = nullptr;
int tex_width, tex_height;
io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height);

for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++)
{
    int rect_id = rect_ids[rect_n];
    if (const ImFontAtlasCustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id))
    {
        // Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here!)
        for (int y = 0; y < rect->Height; y++)
        {
            ImU32* p = (ImU32*)tex_pixels + (rect->Y + y) * tex_width + (rect->X);
            for (int x = rect->Width; x > 0; x--)
                *p++ = IM_COL32(255, 0, 0, 255);
        }
    }
}
Return to Index

About Filenames

Please note that many new C/C++ users have issues loading their files because the filename they provide is wrong due to incorrect assumption of what is the current directory.

Two things to watch for:

(1) In C/C++ and most programming languages if you want to use a backslash \ within a string literal, you need to write it double backslash \\. At it happens, Windows uses backslashes as a path separator, so be mindful.

io.Fonts->AddFontFromFileTTF("MyFiles\MyImage01.jpg", ...);   // This is INCORRECT!!
io.Fonts->AddFontFromFileTTF("MyFiles\\MyImage01.jpg", ...);  // This is CORRECT

In some situations, you may also use / path separator under Windows.

(2) Make sure your IDE/debugger settings starts your executable from the right working (current) directory. In Visual Studio you can change your working directory in project Properties > General > Debugging > Working Directory. People assume that their execution will start from the root folder of the project, where by default it often starts from the folder where object or executable files are stored.

io.Fonts->AddFontFromFileTTF("MyImage01.jpg", ...);       // Relative filename depends on your Working Directory when running your program!
io.Fonts->AddFontFromFileTTF("../MyImage01.jpg", ...);    // Load from the parent folder of your Working Directory
Return to Index

About UTF-8 Encoding

For non-ASCII characters display, a common user issue is not passing correctly UTF-8 encoded strings.

(1) We provide a function ImGui::DebugTextEncoding(const char* text) which you can call to verify the content of your UTF-8 strings. This is a convenient way to confirm that your encoding is correct.

ImGui::SeparatorText("CORRECT");
ImGui::DebugTextEncoding(u8"こんにちは");

ImGui::SeparatorText("INCORRECT");
ImGui::DebugTextEncoding("こんにちは");

UTF-8 Encoding viewer

You can also find this tool under Metrics/Debuggers->Tools->UTF-8 Encoding viewer if you want to paste from clipboard, but this won't validate the UTF-8 encoding done by your compiler.

(2) To encode in UTF-8:

There are also compiler-specific ways to enforce UTF-8 encoding by default:

  • Visual Studio compiler: /utf-8 command-line flag.
  • Visual Studio compiler: #pragma execution_character_set("utf-8") inside your code.
  • Since May 2023 we have changed the Visual Studio projects of all our examples to use /utf-8 (see commit).

Or, since C++11, you can use the u8"my text" syntax to encode literal strings as UTF-8. e.g.:

ImGui::Text(u8"hello");
ImGui::Text(u8"こんにちは");   // this will always be encoded as UTF-8
ImGui::Text("こんにちは");     // the encoding of this is depending on compiler settings/flags and may be incorrect.

Since C++20, because the C++ committee hate its users, they decided to change the u8"" syntax to not return const char* but a new type const char8_t* which doesn't cast to const char*. Because of type usage of u8"" in C++20 is a little more tedious:

ImGui::Text((const char*)u8"こんにちは");

However, you can disable this behavior completely using the compiler option /Zc:char8_t- for MSVC and -fno-char8_t for Clang and GCC.

Return to Index

Debug Tools

Metrics/Debugger->Fonts

You can use the Metrics/Debugger window (available in Demo>Tools) to browse your fonts and understand what's going on if you have an issue. You can also reach it in Demo->Tools->Style Editor->Fonts. The same information are also available in the Style Editor under Fonts.

Fonts debugging

UTF-8 Encoding Viewer**

You can use the UTF-8 Encoding viewer in Metrics/Debugger to verify the content of your UTF-8 strings. From C/C++ code, you can call ImGui::DebugTextEncoding("my string"); function to verify that your UTF-8 encoding is correct.

UTF-8 Encoding viewer

Return to Index

Credits/Licenses For Fonts Included In Repository

Some fonts files are available in the misc/fonts/ folder:

Roboto-Medium.ttf, by Christian Robetson
Apache License 2.0
https://fonts.google.com/specimen/Roboto

Cousine-Regular.ttf, by Steve Matteson
Digitized data copyright (c) 2010 Google Corporation.
Licensed under the SIL Open Font License, Version 1.1
https://fonts.google.com/specimen/Cousine

DroidSans.ttf, by Steve Matteson
Apache License 2.0
https://www.fontsquirrel.com/fonts/droid-sans

ProggyClean.ttf, by Tristan Grimmer
MIT License
(recommended loading setting: Size = 13.0, GlyphOffset.y = +1)
http://www.proggyfonts.net/

ProggyTiny.ttf, by Tristan Grimmer
MIT License
(recommended loading setting: Size = 10.0, GlyphOffset.y = +1)
http://www.proggyfonts.net/

Karla-Regular.ttf, by Jonathan Pinhorn
SIL OPEN FONT LICENSE Version 1.1

Return to Index

ICON FONTS

REGULAR FONTS

MONOSPACE FONTS

Pixel Perfect:

Regular:

Or use Arial Unicode or other Unicode fonts provided with Windows for full characters coverage (not sure of their licensing).

Return to Index