Dear ImGui is an immediate-mode graphical user interface library for C++. It outputs optimized vertex buffers that you render in your application using whatever graphics API you prefer. There are no widget objects to manage, no state to synchronize, and no callback registration. You call functions, Dear ImGui accumulates draw commands, and you render the result. This guide covers everything an administrator, integrator, or developer needs to deploy, configure, optimize, and extend Dear ImGui in production applications.
Table of Contents
- Architecture Overview
- System Requirements
- Configuration Reference
- Deployment & Scaling
- Operations
- Performance
- Security
- Developer Internals
- Integration Points
- Troubleshooting
- Reference
1. Architecture Overview
The Immediate-Mode Paradigm
Dear ImGui follows the immediate-mode GUI (IMGUI) paradigm. Unlike retained-mode toolkits (Qt, GTK, WPF) where you create persistent widget objects, wire up event handlers, and synchronize state between your application data and the UI, Dear ImGui asks you to emit your UI every frame using plain function calls. There is no widget tree to manage, no observer pattern, no data binding. If a checkbox should be visible, you call ImGui::Checkbox(). If a window should exist, you call ImGui::Begin(). The library handles all layout, input processing, and rendering internally — your code simply describes what the UI should look like right now.
This paradigm eliminates an entire class of bugs related to state synchronization. The UI always reflects the current state of your application because it is rebuilt from that state every frame. The cost is that you must call the UI code every frame, but for the kinds of applications Dear ImGui targets (game engines, tools, debug overlays, prototypes), this is already happening.
Data Flow
┌─────────────┐
│ Your App │
└──────┬──────┘
│ 1. Feed inputs (mouse, keyboard, gamepad, display size)
▼
┌──────────────┐
│ ImGuiIO │──── Platform Backend populates this
└──────┬───────┘
│ 2. ImGui::NewFrame()
▼
┌──────────────────────────────────────────────┐
│ Widget Calls │
│ ImGui::Begin("Window") │
│ ImGui::Text("Hello") │
│ if (ImGui::Button("Click")) { DoStuff(); } │
│ ImGui::End() │
└──────────────────┬───────────────────────────┘
│ 3. ImGui::Render()
▼
┌─────────────┐
│ ImDrawData │─── Collection of ImDrawLists
└──────┬──────┘
│ 4. Your renderer iterates draw commands
▼
┌──────────────┐
│ GPU Draw │─── Renderer Backend handles this
│ Calls │
└──────────────┘
Each frame follows this cycle:
- Input: The platform backend (or your code) writes mouse position, button states, keyboard events, display size, and delta time into
ImGuiIO. - NewFrame:
ImGui::NewFrame()processes inputs, updates internal state, and prepares for the new frame. - Widget calls: Your application calls
ImGui::Begin(),ImGui::Text(),ImGui::Button(),ImGui::SliderFloat(), etc. Each call may read from or write to your application variables (e.g., a slider modifies afloat*). Internally, Dear ImGui accumulates geometry (vertices, indices) and draw commands intoImDrawListobjects. - Render:
ImGui::Render()finalizes the frame and producesImDrawData— a collection ofImDrawListobjects with all the vertex/index buffers and draw commands. Your renderer backend iterates this data and issues the corresponding GPU draw calls.
Component Inventory
| Component | File(s) | Role |
|---|---|---|
| Core | imgui.cpp, imgui.h |
Context, windows, input, navigation, settings, ID system, popups, drag-and-drop, keyboard shortcuts |
| Internal | imgui_internal.h |
Internal types and functions — not part of the public API, may change without notice |
| Widgets | imgui_widgets.cpp |
All standard widgets (buttons, sliders, inputs, trees, tabs, menus, selectables, color pickers, multi-select) |
| Tables | imgui_tables.cpp |
Complete table system (columns, headers, sorting, scrolling, freezing, persistence) |
| Drawing | imgui_draw.cpp |
ImDrawList (primitives, polylines, bezier curves), ImFontAtlas (font building, glyph rasterization), texture management |
| Demo | imgui_demo.cpp |
Interactive demo window with inline code samples for every feature |
| Config | imconfig.h |
Compile-time configuration options |
| STB (textedit) | imstb_textedit.h |
Embedded stb_textedit for text input widget internals |
| STB (truetype) | imstb_truetype.h |
Embedded stb_truetype for TrueType font rasterization |
| STB (rectpack) | imstb_rectpack.h |
Embedded stb_rect_pack for font atlas rectangle packing |
Backend Architecture
Dear ImGui separates platform concerns from rendering concerns through a two-backend system:
Platform Backend — Handles the operating system and windowing layer:
- Window size and DPI reporting
- Mouse, keyboard, and gamepad input
- Clipboard access
- IME (Input Method Editor) support
- Mouse cursor shape changes
- File/URL opening via shell
Renderer Backend — Handles GPU interaction:
- Texture creation, updating, and destruction
- Rendering
ImDrawData(vertex/index buffers, draw commands, clip rectangles) - Optional: large mesh support via
VtxOffset - Optional: sampler state management for texture filtering
You combine one platform backend with one renderer backend. For example: GLFW + OpenGL3, SDL3 + Vulkan, Win32 + DirectX11. Some backends (Allegro5) combine both roles.
Technology Stack
- Language: C++ with C++11 as the minimum standard
- External dependencies: None for the core library
- Embedded libraries: stb_truetype, stb_textedit, stb_rect_pack (public domain)
- Optional dependencies: FreeType (font rasterization), plutosvg/lunasvg (SVG font support)
- Build system: None required — add
.cppfiles to your project
Key Design Principles
-
No hidden state: All widget state is either in your variables (passed as pointers to widget functions) or in Dear ImGui's internal state (keyed by widget ID). There are no hidden observer patterns, no event queues the user must poll, and no deferred updates.
-
Predictable lifetime:
CreateContext()allocates,DestroyContext()frees. No garbage collection, no ref-counting, no weak pointers. Memory ownership is explicit. -
Minimal abstraction: Dear ImGui does not abstract the rendering API, the windowing system, or the operating system. It outputs vertex buffers. You render them however you want. This is why Dear ImGui works on every platform that can draw textured triangles.
-
Backward compatibility: The public API (
imgui.h) is treated as stable. Breaking changes are rare and always accompanied by compatibility shims (IMGUI_DISABLE_OBSOLETE_FUNCTIONSremoves them). Internal API (imgui_internal.h) has no stability guarantees. -
Self-contained: The entire library is ~6 files with zero mandatory external dependencies. Vendored stb headers are included. This makes Dear ImGui trivially embeddable in any project.
2. System Requirements
Hardware & Software Requirements
| Requirement | Minimum | Recommended |
|---|---|---|
| Language Standard | C++11 | C++14 or later |
| Compiler | Any C++11-compliant compiler (GCC 4.8+, Clang 3.4+, MSVC 2015+) | Latest stable release of your compiler |
| Operating System | Any (Windows, Linux, macOS, Android, iOS, Emscripten, game consoles) | — |
| Graphics API | Any API capable of rendering textured triangles | OpenGL 3+, DirectX 11+, Vulkan, Metal, WebGPU |
| GPU | Any GPU with programmable shaders (for modern backends) | Dedicated GPU |
| Memory | Minimal — a few MB for context, font atlas, and draw buffers | — |
| Disk | ~2 MB source, font atlas texture in GPU memory | — |
Build Requirements
Dear ImGui requires no special build system. Integration consists of adding source files to your existing build:
Minimum files to compile:
imgui.cpp
imgui_draw.cpp
imgui_tables.cpp
imgui_widgets.cpp
imgui_demo.cpp (optional, but recommended during development)
backends/imgui_impl_* (your chosen platform + renderer backends)
No CMakeLists.txt, no configure script, no package manager entry. Just add the .cpp files to your project's compilation and ensure the header directory is in your include path.
Optional Dependencies
| Dependency | Purpose | Required Headers/Libraries |
|---|---|---|
| FreeType | Higher-quality font rasterization, hinting | freetype.h, link against FreeType library |
| plutosvg | SVG-in-OpenType font support (with FreeType) | PlutoSVG headers + library |
| lunasvg | SVG-in-OpenType font support (with FreeType, alternative to plutosvg) | LunaSVG headers + library |
| stb_sprintf | Faster printf replacement | stb_sprintf.h |
3. Configuration Reference
Dear ImGui supports two layers of configuration: compile-time options set via #define macros (typically in imconfig.h), and runtime options set via the ImGuiIO struct and ImGuiStyle struct.
3.1 Compile-Time Options (imconfig.h)
All compile-time options are set by defining macros before imgui.h is included. The recommended approach is to edit imconfig.h (which is included by imgui.h). Alternatively, you can define macros in your build system's preprocessor definitions.
Important
Every compilation unit that includes
imgui.hmust see the sameimconfig.hdefines. Mismatched defines across translation units cause subtle memory corruption and crashes. UseIMGUI_CHECKVERSION()in your main file to detect version/configuration mismatches at runtime.
Assert & Debug
| Define | Type | Default | Description |
|---|---|---|---|
IM_ASSERT(expr) |
Macro override | assert(expr) |
Override the assertion macro. Receives a boolean expression. Common override: log + break, or throw an exception. |
IM_DEBUG_BREAK |
Macro override | Platform-detected (__debugbreak(), __builtin_debugtrap(), raise(SIGTRAP), etc.) |
Override the debug break instruction used by the debug tools. |
IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS |
Flag | Not defined | When defined, highlights ALL conflicting ID items (not just the first pair). Expensive — for debugging only. |
IMGUI_DEBUG_PARANOID |
Flag | Not defined | Enable slower, stricter assertions throughout the codebase. Development/CI use only. |
IMGUI_ENABLE_TEST_ENGINE |
Flag | Not defined | Enable hooks for the Dear ImGui Test Engine (ocornut/imgui_test_engine). |
API Visibility & DLL
| Define | Type | Default | Description |
|---|---|---|---|
IMGUI_API |
Macro override | Empty | Decoration for public API symbols. Set to __declspec(dllexport) or __declspec(dllimport) for shared library builds. |
IMGUI_IMPL_API |
Macro override | IMGUI_API |
Decoration for backend implementation symbols. Can differ from IMGUI_API if backends are in a separate DLL. |
Feature Disabling
| Define | Type | Default | Description |
|---|---|---|---|
IMGUI_DISABLE |
Flag | Not defined | Disable everything except ImVec2, ImVec4, ImColor, ImGuiStorage, and callbacks. For use when you only need data types. |
IMGUI_DISABLE_DEMO_WINDOWS |
Flag | Not defined | Remove ShowDemoWindow(), ShowStyleEditor(), ShowUserGuide() and the entire demo code. Saves ~100KB in binary. |
IMGUI_DISABLE_DEBUG_TOOLS |
Flag | Not defined | Remove ShowMetricsWindow(), ShowDebugLogWindow(), ShowIDStackToolWindow(), DebugStartItemPicker(), and debug logging. |
IMGUI_DISABLE_OBSOLETE_FUNCTIONS |
Flag | Not defined | Remove all obsolete/deprecated function wrappers. Recommended for new projects to avoid using deprecated API. |
Platform-Specific Disabling
| Define | Type | Default | Description |
|---|---|---|---|
IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS |
Flag | Not defined | Disable the default Win32 clipboard implementation. |
IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS |
Flag | Not defined | Enable the old default Win32 IME implementation (now usually handled by backends). |
IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS |
Flag | Not defined | Disable the default Win32 IME handler. |
IMGUI_DISABLE_WIN32_FUNCTIONS |
Flag | Not defined | Disable all Win32 functions (clipboard, IME, etc.). Useful for MinGW/Cygwin builds that may not link Win32 libraries. |
IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS |
Flag | Not defined | Enable macOS NSPasteboard clipboard implementation. |
IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS |
Flag | Not defined | Disable the default Platform_OpenInShellFn implementation (ShellExecute on Windows, open/xdg-open on Unix). |
Standard Library Overrides
| Define | Type | Default | Description |
|---|---|---|---|
IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS |
Flag | Not defined | Disable default ImFormatString() / ImFormatStringV() implementations. You must provide replacements. |
IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS |
Flag | Not defined | Disable default ImFabs(), ImSqrt(), ImAtan2(), etc. You must provide replacements. |
IMGUI_DISABLE_FILE_FUNCTIONS |
Flag | Not defined | Disable all file I/O functions (ImFileOpen, ImFileClose, etc.) AND .ini settings loading/saving. |
IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS |
Flag | Not defined | Disable only the default implementations of file I/O functions (you can provide your own). .ini support remains. |
IMGUI_DISABLE_DEFAULT_ALLOCATORS |
Flag | Not defined | Disable the default malloc/free-based allocators. You must call SetAllocatorFunctions() before CreateContext(). |
IMGUI_DISABLE_DEFAULT_FONT |
Flag | Not defined | Do not embed the default font (ProggyClean 13px). You must load a font manually before building the font atlas. |
IMGUI_DISABLE_SSE |
Flag | Not defined | Disable SSE intrinsics for ImVec2/ImVec4 operations even when available. |
STB Library Overrides
| Define | Type | Default | Description |
|---|---|---|---|
IMGUI_STB_TRUETYPE_FILENAME |
String | "imstb_truetype.h" |
Path to an alternative stb_truetype header. |
IMGUI_STB_RECT_PACK_FILENAME |
String | "imstb_rectpack.h" |
Path to an alternative stb_rect_pack header. |
IMGUI_STB_SPRINTF_FILENAME |
String | "stb_sprintf.h" |
Path to stb_sprintf header (used when IMGUI_USE_STB_SPRINTF is defined). |
IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION |
Flag | Not defined | Skip #define STB_TRUETYPE_IMPLEMENTATION — use if you compile stb_truetype separately. |
IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION |
Flag | Not defined | Skip #define STB_RECT_PACK_IMPLEMENTATION — use if you compile stb_rect_pack separately. |
IMGUI_USE_STB_SPRINTF |
Flag | Not defined | Use stb_sprintf.h for formatting instead of snprintf. Must also set IMGUI_STB_SPRINTF_FILENAME if header is not at the default path. |
Font & Rendering
| Define | Type | Default | Description |
|---|---|---|---|
IMGUI_ENABLE_FREETYPE |
Flag | Not defined | Use FreeType for font rasterization instead of stb_truetype. Requires linking FreeType. Include misc/freetype/imgui_freetype.cpp in your build. |
IMGUI_ENABLE_FREETYPE_PLUTOSVG |
Flag | Not defined | Enable SVG font support in FreeType via PlutoSVG. Requires PlutoSVG library. |
IMGUI_ENABLE_FREETYPE_LUNASVG |
Flag | Not defined | Enable SVG font support in FreeType via LunaSVG. Requires LunaSVG library. |
IMGUI_ENABLE_STB_TRUETYPE |
Flag | Not defined | Force stb_truetype even when FreeType is enabled. Allows both rasterizers to coexist. |
IMGUI_USE_BGRA_PACKED_COLOR |
Flag | Not defined | Use BGRA byte order for packed colors instead of RGBA. Matches DirectX default. Affects ImGui::ColorConvertFloat4ToU32() output. |
IMGUI_USE_WCHAR32 |
Flag | Not defined | Use 32-bit ImWchar (default is 16-bit). Required for full Unicode support beyond BMP (Basic Multilingual Plane). |
IMGUI_USE_LEGACY_CRC32_ADLER |
Flag | Not defined | Use the old Adler-style CRC32 implementation instead of the standard CRC32 table. For backward compatibility with older .ini files. |
Type Overrides
| Define | Type | Default | Description |
|---|---|---|---|
ImDrawIdx |
Type override | unsigned short (16-bit) |
Override the index buffer type. Set to unsigned int for meshes with more than 65535 vertices per ImDrawList. |
ImDrawCallback |
Type override | void (*)(const ImDrawList*, const ImDrawCmd*) |
Override the draw callback function pointer type. |
ImTextureID |
Type override | ImU64 |
Override the texture identifier type. Must be pointer-sized or smaller. Common overrides: void*, GLuint, ID3D11ShaderResourceView*. |
ImTextureID_Invalid |
Value override | 0 |
The "null" or "invalid" value for ImTextureID. Must correspond to a value that your renderer treats as "no texture." |
Extension Points
| Define | Type | Default | Description |
|---|---|---|---|
IM_VEC2_CLASS_EXTRA |
Code block | Not defined | Inject additional members/methods into the ImVec2 struct. Typically used to add implicit conversions to/from your engine's vector type. |
IM_VEC4_CLASS_EXTRA |
Code block | Not defined | Inject additional members/methods into the ImVec4 struct. Same use case as IM_VEC2_CLASS_EXTRA. |
IMGUI_INCLUDE_IMGUI_USER_H |
Flag | Not defined | Automatically #include "imgui_user.h" at the end of imgui.h. Legacy mechanism — prefer IMGUI_USER_H_FILENAME for custom filenames. |
IMGUI_USER_H_FILENAME |
String | "imgui_user.h" |
Custom filename for the user include. Only used if IMGUI_INCLUDE_IMGUI_USER_H is defined. |
IMGUI_DEFINE_MATH_OPERATORS |
Flag | Defined by imgui_internal.h |
Define ImVec2/ImVec4 math operators (+, -, *, /). Automatically defined when including imgui_internal.h. Define it yourself if you need operators with only imgui.h. |
3.2 ImGuiIO Runtime Configuration
The ImGuiIO struct is accessed via ImGui::GetIO() and contains all runtime configuration, input data, and output status. Set configuration fields after CreateContext() and before the first NewFrame().
Configuration Flags
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable keyboard nav
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable gamepad nav
| Field | Type | Default | Description |
|---|---|---|---|
ConfigFlags |
ImGuiConfigFlags |
0 |
Combination of ImGuiConfigFlags_ values. See flag table below. |
BackendFlags |
ImGuiBackendFlags |
0 |
Set by the backend to inform Dear ImGui of capabilities. See flag table below. |
DisplaySize |
ImVec2 |
(0,0) |
Application display size in pixels. Must be set every frame (typically by the platform backend). |
DeltaTime |
float |
1.0f/60.0f |
Time elapsed since last frame in seconds. Must be set every frame. |
IniFilename |
const char* |
"imgui.ini" |
Path to the .ini settings file. Set to NULL to disable automatic loading/saving. |
LogFilename |
const char* |
"imgui_log.txt" |
Path to the text logging output file. Set to NULL to disable. |
UserData |
void* |
NULL |
Store your own data for callbacks and custom use. |
Font Configuration
| Field | Type | Default | Description |
|---|---|---|---|
FontDefault |
ImFont* |
NULL |
Font to use when no font is specified. If NULL, uses the first font added to the atlas. |
FontGlobalScale |
float |
1.0f |
Obsolete in 1.92+. Previously used for global font scaling. Use style.FontSizeBase and style.FontScaleMain instead. |
Input Behavior
| Field | Type | Default | Description |
|---|---|---|---|
ConfigInputTextCursorBlink |
bool |
true |
Enable blinking cursor in InputText widgets. |
ConfigInputTextEnterKeepActive |
bool |
false |
When true, pressing Enter in an InputText field keeps the field active instead of deactivating it. |
MouseDragThreshold |
float |
6.0f |
Distance threshold (in pixels) before a mouse drag is registered. |
KeyRepeatDelay |
float |
0.275f |
Delay in seconds before keyboard key repeat starts. |
KeyRepeatRate |
float |
0.050f |
Rate of keyboard key repeat in seconds. |
Window Behavior
| Field | Type | Default | Description |
|---|---|---|---|
ConfigWindowsResizeFromEdges |
bool |
true |
Enable resizing windows from their edges and lower-left corner. Requires BackendFlags_HasMouseCursors for visual feedback. |
ConfigWindowsMoveFromTitleBarOnly |
bool |
false |
When true, windows can only be moved by dragging the title bar. When false, any unoccupied area works. |
ConfigScrollbarScrollByPage |
bool |
true |
Enable scrolling by page when clicking the scrollbar body. |
Debug Configuration
| Field | Type | Default | Description |
|---|---|---|---|
ConfigDebugHighlightIdConflicts |
bool |
true |
Highlight items that share the same ID. Helps detect PushID/PopID errors. |
ConfigDebugIsDebuggerPresent |
bool |
false |
Set to true to enable IM_DEBUG_BREAK calls on certain errors. Backends may auto-detect this. |
Output Status (Read-Only)
| Field | Type | Description |
|---|---|---|
WantCaptureMouse |
bool |
Dear ImGui wants to capture mouse input. Your application should not process mouse events when true. |
WantCaptureKeyboard |
bool |
Dear ImGui wants to capture keyboard input. Your application should not process keyboard events when true. |
WantTextInput |
bool |
Dear ImGui wants text input. Mobile/console apps should show an on-screen keyboard. |
WantSaveIniSettings |
bool |
Dear ImGui wants to save .ini settings. If you handle saving yourself (manual save), check this flag. |
Framerate |
float |
Estimated frames per second, averaged over 60 frames. For display/debugging. |
3.3 ImGuiStyle Reference
The ImGuiStyle struct controls the visual appearance of all Dear ImGui elements. Access via ImGui::GetStyle(). All distances are in pixels. Colors are stored as ImVec4 (RGBA float, 0.0–1.0).
Tip
Call
ImGui::ShowStyleEditor()to interactively tweak every style variable in real time. You can copy the resulting values as code. This is the fastest way to customize the look of your UI.
Size & Spacing
| Member | Type | Default | Description |
|---|---|---|---|
Alpha |
float |
1.0f |
Global alpha multiplier for all Dear ImGui rendering. Useful for fade-in/fade-out. |
DisabledAlpha |
float |
0.6f |
Alpha multiplier applied on top of Alpha for disabled items (BeginDisabled()). |
WindowPadding |
ImVec2 |
(8, 8) |
Padding inside window frames. |
WindowRounding |
float |
0.0f |
Corner rounding radius for windows. Set to 0.0f for sharp corners. |
WindowBorderSize |
float |
1.0f |
Thickness of window borders. Set to 0.0f for no borders. |
WindowMinSize |
ImVec2 |
(32, 32) |
Minimum window size (enforced by system). |
WindowTitleAlign |
ImVec2 |
(0.0f, 0.5f) |
Title bar text alignment. (0.0, 0.5) = left-centered, (0.5, 0.5) = centered. |
ChildRounding |
float |
0.0f |
Corner rounding radius for child windows. |
ChildBorderSize |
float |
1.0f |
Border thickness for child windows. |
PopupRounding |
float |
0.0f |
Corner rounding radius for popup windows. |
PopupBorderSize |
float |
1.0f |
Border thickness for popup windows. |
FramePadding |
ImVec2 |
(4, 3) |
Padding inside framed widgets (buttons, input fields, etc.). |
FrameRounding |
float |
0.0f |
Corner rounding radius for framed widgets. |
FrameBorderSize |
float |
0.0f |
Border thickness for framed widgets. |
ItemSpacing |
ImVec2 |
(8, 4) |
Spacing between widgets on the same line or between lines. |
ItemInnerSpacing |
ImVec2 |
(4, 4) |
Spacing between elements within a composite widget (e.g., label and slider). |
CellPadding |
ImVec2 |
(4, 2) |
Padding within table cells. |
IndentSpacing |
float |
21.0f |
Horizontal indentation for TreeNode, Indent(). |
ColumnsMinSpacing |
float |
6.0f |
Minimum horizontal spacing between two columns (legacy columns API). |
ScrollbarSize |
float |
14.0f |
Width of vertical scrollbars, height of horizontal scrollbars. |
ScrollbarRounding |
float |
9.0f |
Corner rounding radius for scrollbar grab handles. |
GrabMinSize |
float |
12.0f |
Minimum size of slider/scrollbar grab handles. |
GrabRounding |
float |
0.0f |
Corner rounding radius for grab handles. |
TabRounding |
float |
4.0f |
Corner rounding radius for tabs. |
TabBorderSize |
float |
0.0f |
Border thickness for tabs. |
TabBarBorderSize |
float |
1.0f |
Thickness of the border/separator line below tab bars. |
TabBarOverlineSize |
float |
2.0f |
Thickness of the overline above the selected tab. |
ImageBorderSize |
float |
0.0f |
Border thickness around Image() widgets. Uses ImGuiCol_Border color. |
SeparatorTextBorderSize |
float |
3.0f |
Thickness of the line in SeparatorText(). |
SeparatorTextAlign |
ImVec2 |
(0.0f, 0.5f) |
Text alignment within SeparatorText(). |
SeparatorTextPadding |
ImVec2 |
(20, 3) |
Padding around SeparatorText() text. |
Font Sizing (1.92+)
| Member | Type | Default | Description |
|---|---|---|---|
FontSizeBase |
float |
0.0f |
Base font size in pixels. When 0.0f, uses FontDefault->FontSize. This replaces the old per-font-atlas sizing model. |
FontScaleMain |
float |
1.0f |
Main font scale multiplier. Multiplied with FontSizeBase to get the actual rendering size. |
FontScaleDpi |
float |
1.0f |
DPI-related font scale. Typically set by the platform backend based on display DPI. Combined with FontScaleMain. |
Tree Lines (1.92+)
| Member | Type | Default | Description |
|---|---|---|---|
TreeLinesFlags |
ImGuiTreeNodeFlags |
0 |
Default flags for tree node connecting lines. Use ImGuiTreeNodeFlags_DrawLinesV or ImGuiTreeNodeFlags_DrawLinesFull. |
TreeLinesSize |
float |
1.0f |
Line thickness for tree node connecting lines. |
Rendering Quality
| Member | Type | Default | Description |
|---|---|---|---|
AntiAliasedLines |
bool |
true |
Enable anti-aliasing on lines and borders. Disable for slight performance gain on very low-end hardware. |
AntiAliasedLinesUseTex |
bool |
true |
Enable texture-based anti-aliasing for lines. Faster than geometric AA on most hardware. Requires bilinear filtering on the font atlas texture. |
AntiAliasedFill |
bool |
true |
Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.). |
CurveTessellationTol |
float |
1.25f |
Tolerance for bezier curve tessellation. Lower = smoother curves but more vertices. |
CircleTessellationMaxError |
float |
0.30f |
Maximum error for circle/arc tessellation in pixels. Lower = rounder circles but more vertices. |
Mouse Cursor
| Member | Type | Default | Description |
|---|---|---|---|
MouseCursorScale |
float |
1.0f |
Scale for software-rendered mouse cursors (when backend doesn't support hardware cursors). Not commonly needed. |
Hover & Tooltip Timing
| Member | Type | Default | Description |
|---|---|---|---|
HoverStationaryDelay |
float |
0.15f |
Delay (seconds) before an item is considered "stationary" for hover purposes. |
HoverDelayShort |
float |
0.15f |
Short hover delay (used for ImGuiHoveredFlags_DelayShort). |
HoverDelayNormal |
float |
0.40f |
Normal hover delay (used for ImGuiHoveredFlags_DelayNormal). |
HoverFlagsForTooltipMouse |
ImGuiHoveredFlags |
ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled |
Default hover flags for tooltips triggered by mouse hovering. |
HoverFlagsForTooltipNav |
ImGuiHoveredFlags |
ImGuiHoveredFlags_AllowWhenDisabled |
Default hover flags for tooltips triggered by keyboard/gamepad navigation. |
Colors
The Colors[] array (indexed by ImGuiCol_ enum values) controls all widget colors. There are 58 color entries. See the ImGuiCol_ enum in section 3.4 for the complete list. Use ImGui::PushStyleColor() / PopStyleColor() for per-widget overrides, or modify style.Colors[] directly for global changes.
3.4 All Flag Enumerations
ImGuiConfigFlags_
| Flag | Value | Description |
|---|---|---|
NavEnableKeyboard |
1 << 0 |
Master keyboard navigation enable. Calls io.WantCaptureKeyboard when active. |
NavEnableGamepad |
1 << 1 |
Master gamepad navigation enable. Requires backend to set BackendFlags_HasGamepad. |
NoMouseCursorChange |
1 << 5 |
Prevent Dear ImGui from changing the mouse cursor shape. |
NoKeyboard |
1 << 4 |
Disable keyboard input entirely. |
ImGuiBackendFlags_
| Flag | Value | Description |
|---|---|---|
HasGamepad |
1 << 0 |
Backend has gamepad support. |
HasMouseCursors |
1 << 1 |
Backend supports changing the OS mouse cursor shape. |
HasSetMousePos |
1 << 2 |
Backend supports repositioning the OS mouse. |
RendererHasVtxOffset |
1 << 3 |
Backend renderer supports ImDrawCmd::VtxOffset for large meshes. |
RendererHasTextures |
1 << 4 |
Backend renderer supports the platform_io.Textures[] system for dynamic texture management. New in 1.92. |
ImGuiWindowFlags_
| Flag | Description |
|---|---|
NoTitleBar |
Disable the title bar. |
NoResize |
Disable user resizing via the corner grip. |
NoMove |
Disable user moving the window. |
NoScrollbar |
Disable scrollbars (content can still scroll programmatically). |
NoScrollWithMouse |
Disable mouse wheel scrolling. |
NoCollapse |
Disable user collapsing the window via double-click on the title bar. |
AlwaysAutoResize |
Resize the window to fit its contents every frame. |
NoBackground |
Disable drawing the background and border. Similar to a transparent window. |
NoSavedSettings |
Never persist position/size in .ini file. |
NoMouseInputs |
Disable all mouse interaction (pass-through). |
MenuBar |
Window has a menu bar. |
HorizontalScrollbar |
Allow horizontal scrollbar. |
NoFocusOnAppearing |
Disable taking focus when transitioning from hidden to visible. |
NoBringToFrontOnFocus |
Disable bringing window to front when taking focus. |
AlwaysVerticalScrollbar |
Always show the vertical scrollbar. |
AlwaysHorizontalScrollbar |
Always show the horizontal scrollbar. |
NoNavInputs |
Disable gamepad/keyboard navigation within the window. |
NoNavFocus |
Disable window receiving focus via navigation (Ctrl+Tab). |
UnsavedDocument |
Show a dot on the tab/title bar when the tab bar is focused. |
NoNav |
Shortcut for NoNavInputs | NoNavFocus. |
NoDecoration |
Shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse. |
NoInputs |
Shortcut for NoMouseInputs | NoNavInputs | NoNavFocus. |
ChildWindow |
Internal use: set by BeginChild(). |
Tooltip |
Internal use: set by tooltip functions. |
Popup |
Internal use: set by BeginPopup(). |
Modal |
Internal use: set by BeginPopupModal(). |
ChildMenu |
Internal use: set by BeginMenu(). |
ImGuiChildFlags_
| Flag | Description |
|---|---|
Borders |
Show a border around the child window (equivalent to ImGuiWindowFlags_Border). |
AlwaysUseWindowPadding |
Use style.WindowPadding even if no border is applied. |
ResizeX |
Allow horizontal resizing via the right border. |
ResizeY |
Allow vertical resizing via the bottom border. |
AutoResizeX |
Auto-fit width to content. Combined with ResizeX, allows shrinking back to content size. |
AutoResizeY |
Auto-fit height to content. Combined with ResizeY, allows shrinking back to content size. |
AlwaysAutoResize |
Combined with AutoResizeX/AutoResizeY, auto-resize every frame. |
FrameStyle |
Style the child as a framed item (using FramePadding, FrameRounding, FrameBorderSize, FrameBg color). |
NavFlattened |
Flatten navigation: share focus scope with parent, allow navigation to cross between parent and child. |
ImGuiInputTextFlags_
| Flag | Description |
|---|---|
CharsDecimal |
Allow 0123456789.+-*/ |
CharsHexadecimal |
Allow 0123456789ABCDEFabcdef |
CharsScientific |
Allow 0123456789.+-*/eE (for scientific notation input) |
CharsUppercase |
Convert characters to uppercase. |
CharsNoBlank |
Filter out spaces and tabs. |
AllowTabInput |
Tab key inserts a tab character instead of moving focus. |
EnterReturnsTrue |
Return true when Enter is pressed (instead of on every value change). |
EscapeClearsAll |
Escape clears the text field (first press clears to empty). |
CtrlEnterForNewLine |
In multiline mode, Ctrl+Enter inserts a newline (Enter alone returns true). |
ReadOnly |
Text is read-only, but can still be selected and copied. |
Password |
Display * instead of characters, disable copy. |
AlwaysOverwrite |
Overwrite mode (not insert mode). |
AutoSelectAll |
Select entire text when the widget is first activated. |
ParseEmptyRefVal |
Parse empty input as 0 for scalar input widgets. |
DisplayEmptyRefVal |
Display 0 as empty string for scalar input widgets. |
NoHorizontalScroll |
Disable horizontal scrolling in multiline input. |
NoUndoRedo |
Disable undo/redo history. |
ElideLeft |
When text doesn't fit, elide the left side and keep the right (for paths, etc.). |
CallbackCompletion |
Invoke callback on pressing Tab (for auto-completion). |
CallbackHistory |
Invoke callback on pressing Up/Down (for history navigation). |
CallbackAlways |
Invoke callback on every edit. |
CallbackCharFilter |
Invoke callback on character input for custom filtering. |
CallbackResize |
Invoke callback when buffer capacity needs to grow (for dynamic strings). |
CallbackEdit |
Invoke callback on any edit (unlike CallbackAlways, not called for input-unrelated events). |
ImGuiTreeNodeFlags_
| Flag | Description |
|---|---|
Selected |
Draw as selected. |
Framed |
Draw frame with background (FrameRounding, FramePadding). Full row highlight. |
AllowOverlap |
Allow other items to overlap this one (for custom hit testing). |
NoTreePushOnOpen |
Don't call TreePush() when open. No extra indent or ID push. |
NoAutoOpenOnLog |
Don't auto-open when the logging/capture system is active. |
DefaultOpen |
Start as open by default. |
OpenOnDoubleClick |
Require double-click to open (instead of single click). |
OpenOnArrow |
Only open when clicking the arrow part (not the full label). |
Leaf |
No collapsing, no arrow (acts as a selectable leaf node). |
Bullet |
Display a bullet instead of an arrow. |
FramePadding |
Use FramePadding (even without Framed) to vertically align text with tree nodes. |
SpanAvailWidth |
Extend hit area to the right-most edge (even if not Framed). |
SpanFullWidth |
Extend hit area to the full width of the window (past IndentSpacing). |
SpanLabelWidth |
Narrow hit area to just the label text. |
SpanAllColumns |
Span across all table columns when used inside a table. |
NavLeftJumpsBackHere |
Left-arrow navigation jumps back to this node. |
DrawLinesV |
Draw vertical connecting lines. |
DrawLinesFull |
Draw vertical + horizontal connecting lines. |
CollapsingHeader |
Shortcut for Framed | NoTreePushOnOpen | NoAutoOpenOnLog. |
ImGuiPopupFlags_
| Flag | Description |
|---|---|
MouseButtonLeft |
Open on left mouse button (default for OpenPopupOnItemClick). |
MouseButtonRight |
Open on right mouse button (default for BeginPopupContextItem). |
MouseButtonMiddle |
Open on middle mouse button. |
NoReopen |
Don't reopen the popup if already open (prevent flickering on repeated right-clicks). |
NoOpenOverExistingPopup |
Don't open if there is already a popup at the same level of the popup stack. |
NoOpenOverItems |
For BeginPopupContextWindow(): don't open over items; only open on empty space. |
AnyPopupId |
For IsPopupOpen(): match any popup regardless of ID. |
AnyPopupLevel |
For IsPopupOpen(): match at any popup stack level (not just the current level). |
AnyPopup |
Shortcut for AnyPopupId | AnyPopupLevel. |
ImGuiSelectableFlags_
| Flag | Description |
|---|---|
NoAutoClosePopups |
Clicking does not automatically close the parent popup. |
SpanAllColumns |
Span across all columns when in a table. |
AllowDoubleClick |
Return true on double-click instead of single click. |
Disabled |
Cannot be selected, grayed out text. |
AllowOverlap |
Allow other items to overlap for custom rendering. |
Highlight |
Draw as highlighted/hovered even when not hovered. |
ImGuiComboFlags_
| Flag | Description |
|---|---|
PopupAlignLeft |
Align the combo popup left instead of right-aligning with the button. |
HeightSmall |
Max ~4 items visible. |
HeightRegular |
Max ~8 items visible (default). |
HeightLarge |
Max ~20 items visible. |
HeightLargest |
As tall as possible (limited by screen height). |
NoArrowButton |
Don't display the arrow button. |
NoPreview |
Don't display the current selected item text. |
WidthFitPreview |
Size the combo width to fit the preview text (not the label). |
ImGuiTabBarFlags_
| Flag | Description |
|---|---|
Reorderable |
Allow tabs to be reordered by dragging. |
AutoSelectNewTabs |
Automatically select newly created tabs. |
TabListPopupButton |
Show a popup button to list all tabs on overflow. |
NoCloseWithMiddleMouseButton |
Disable closing tabs with the middle mouse button. |
NoTabListScrollingButtons |
Disable scrolling buttons when tabs overflow (replaced by popup or arrows). |
NoTooltip |
Disable tooltips on hovering the tab. |
DrawSelectedOverline |
Draw an overline on the selected tab. Default for docked windows. |
FittingPolicyResizeDown |
Shrink tabs when they overflow. |
FittingPolicyScroll |
Add scroll buttons when tabs overflow. |
ImGuiTabItemFlags_
| Flag | Description |
|---|---|
UnsavedDocument |
Show a dot indicator on the tab title. |
SetSelected |
Force this tab to be selected on the next frame. |
NoCloseWithMiddleMouseButton |
Disable closing this tab with the middle mouse button. |
NoPushId |
Don't call PushID(); the caller manages the ID stack. |
NoTooltip |
Disable tooltip for this tab. |
NoReorder |
Disable reordering of this tab. |
Leading |
Tab is always positioned at the beginning of the tab bar. |
Trailing |
Tab is always positioned at the end of the tab bar. |
NoAssumedClosure |
Tab closure not assumed on click (for confirmation dialogs). |
ImGuiTableFlags_
| Flag | Description |
|---|---|
| Sizing | |
SizingFixedFit |
Columns default to _WidthFixed. Fixed width, no stretch. |
SizingFixedSame |
Columns default to _WidthFixed. All columns have the same width. |
SizingStretchProp |
Columns default to _WidthStretch. Proportional widths. |
SizingStretchSame |
Columns default to _WidthStretch. Equal widths. |
| Decorations | |
Resizable |
Allow column resizing by dragging borders. |
Reorderable |
Allow column reordering via drag-and-drop headers. |
Hideable |
Allow hiding columns via the context menu. |
Sortable |
Allow sorting by clicking headers. Use TableGetSortSpecs(). |
HighlightHoveredColumn |
Highlight the column header when hovered. |
ContextMenuInBody |
Open the context menu on right-clicking the body (not just headers). |
| Borders | |
BordersInnerH |
Horizontal borders between rows. |
BordersOuterH |
Horizontal border on top and bottom. |
BordersInnerV |
Vertical borders between columns. |
BordersOuterV |
Vertical border on left and right. |
BordersH |
All horizontal borders. |
BordersV |
All vertical borders. |
BordersInner |
Inner horizontal + vertical borders. |
BordersOuter |
Outer horizontal + vertical borders. |
Borders |
All borders. |
| Background | |
RowBg |
Alternating row background colors (ImGuiCol_TableRowBg, ImGuiCol_TableRowBgAlt). |
NoBordersInBody |
Disable vertical borders in the body (borders in headers only). |
NoBordersInBodyUntilResize |
Same as above, but re-enable on column resize. |
| Layout | |
NoHostExtendX |
Don't extend the table to fill available width. |
NoHostExtendY |
Don't extend the table to fill available height (for ScrollY). |
NoKeepColumnsVisible |
Allow columns to be fully clipped (instead of keeping a minimum visible). |
PreciseWidths |
Disable distributing remainder width across columns. More precise but causes jitter when resizing. |
| Scrolling | |
ScrollX |
Enable horizontal scrolling. |
ScrollY |
Enable vertical scrolling. Requires a fixed outer size. |
| Padding | |
NoPadOuterX |
Remove outer padding. |
NoPadInnerX |
Remove inner padding between columns. |
| Clipping | |
NoClip |
Don't clip contents. Allows sampling outside column boundaries. |
ImGuiTableColumnFlags_
| Flag | Description |
|---|---|
Disabled |
Master disable flag. Column is hidden and excluded from width calculation. |
DefaultHide |
Hidden by default (user can show via context menu). |
DefaultSort |
Default sort column. |
WidthStretch |
Column stretches to fill available width (weighted by stretch factor). |
WidthFixed |
Column has a fixed width. |
NoResize |
Disable manual resizing of this column. |
NoReorder |
Disable reordering of this column. |
NoHide |
Disable hiding this column via the context menu. |
NoClip |
Disable clipping for this column (all columns with NoClip will share a common draw command). |
NoSort |
Disable sorting on this column. |
NoSortAscending |
Disable ascending sort on this column. |
NoSortDescending |
Disable descending sort on this column. |
NoHeaderLabel |
Don't display the column header text. |
NoHeaderWidth |
Header width doesn't contribute to auto-column-width. |
PreferSortAscending |
Initial sort direction is ascending (default). |
PreferSortDescending |
Initial sort direction is descending. |
IndentEnable |
Use current IndentSpacing for this column (default for column 0). |
IndentDisable |
Don't apply IndentSpacing for this column (default for columns > 0). |
AngledHeader |
This column has an angled header. |
IsEnabled |
Status flag (read-only): column is enabled (not hidden). |
IsVisible |
Status flag (read-only): column is visible (not clipped). |
IsSorted |
Status flag (read-only): column is part of the current sort spec. |
IsHovered |
Status flag (read-only): column header is being hovered. |
ImGuiTableRowFlags_
| Flag | Description |
|---|---|
Headers |
Identify this row as a header row. Changes default color. Used by TableHeadersRow(). |
ImGuiTableBgTarget_
| Value | Description |
|---|---|
RowBg0 |
Set the background color of the row (use TableSetBgColor()). |
RowBg1 |
Set the alternate background color of the row. |
CellBg |
Set the background color of the individual cell. |
ImGuiItemFlags_
| Flag | Description |
|---|---|
NoTabStop |
Item cannot be focused via Tab key. |
NoNav |
Item does not participate in navigation (keyboard/gamepad). |
NoNavDefaultFocus |
Item will not receive default focus via SetItemDefaultFocus(). |
ButtonRepeat |
Button clicks repeat when held down. |
AutoClosePopups |
Automatically close the parent popup when this item is activated (default behavior for MenuItem, Selectable). |
ImGuiFocusedFlags_
| Flag | Description |
|---|---|
ChildWindows |
Consider child windows of the focused window. |
RootWindow |
Test from the root window (ignore child hierarchy). |
AnyWindow |
Return true if any window is focused. |
NoPopupHierarchy |
Don't traverse into popup windows. |
RootAndChildWindows |
Shortcut for RootWindow | ChildWindows. |
ImGuiHoveredFlags_
| Flag | Description |
|---|---|
ChildWindows |
Consider child windows. |
RootWindow |
Test from the root window. |
AnyWindow |
Return true if any window is hovered. |
NoPopupHierarchy |
Don't traverse into popup windows. |
AllowWhenBlockedByPopup |
Return true even if a popup is blocking interaction. |
AllowWhenBlockedByActiveItem |
Return true even if an active item is blocking hover. |
AllowWhenOverlappedByItem |
Return true even if another item is overlapping. |
AllowWhenOverlappedByWindow |
Return true even if another window is overlapping. |
AllowWhenDisabled |
Return true even if the item is disabled. |
NoNavOverride |
Don't override hovering of the navigation focused item. |
AllowWhenOverlapped |
Shortcut for AllowWhenOverlappedByItem | AllowWhenOverlappedByWindow. |
RectOnly |
Shortcut for AllowWhenBlockedByPopup | AllowWhenBlockedByActiveItem | AllowWhenOverlapped. |
RootAndChildWindows |
Shortcut for RootWindow | ChildWindows. |
ForTooltip |
Use tooltip-specific hover timing/flags. |
Stationary |
Require the mouse to be stationary. |
DelayNone |
No hover delay. |
DelayShort |
Use the short hover delay (style.HoverDelayShort). |
DelayNormal |
Use the normal hover delay (style.HoverDelayNormal). |
NoSharedDelay |
Don't share the hover delay timer with sibling items. |
ImGuiDragDropFlags_
| Flag | Description |
|---|---|
| Source flags | |
SourceNoPreviewTooltip |
Don't show the preview tooltip during drag. |
SourceNoDisableHover |
Don't disable hover feedback when dragging. |
SourceNoHoldToOpenOthers |
Don't open tree nodes by hovering while dragging. |
SourceAllowNullID |
Allow drag from items with no unique ID (text, images). |
SourceExtern |
External drag source (from outside Dear ImGui). Calls IsMouseReleased(). |
PayloadAutoExpire |
Automatically expire the payload if not dropped. |
PayloadNoCrossContext |
Don't allow the payload to cross ImGui contexts. |
PayloadNoCrossProcess |
Don't allow the payload to cross process boundaries. |
| Accept flags | |
AcceptBeforeDelivery |
Peek at the payload (return true before mouse release). |
AcceptNoDrawDefaultRect |
Don't draw the default yellow highlight rectangle. |
AcceptNoPreviewTooltip |
Hide the tooltip on the accept target. |
AcceptPeekOnly |
Shortcut for AcceptBeforeDelivery | AcceptNoDrawDefaultRect. |
ImGuiColorEditFlags_
| Flag | Description |
|---|---|
NoAlpha |
Hide the alpha channel (no alpha edit or display). |
NoPicker |
Disable the color picker when clicking the colored square. |
NoOptions |
Disable the right-click options menu. |
NoSmallPreview |
Don't show the small square preview next to the input. |
NoInputs |
Don't show the input fields (hex, RGB, HSV). |
NoTooltip |
Don't show a tooltip with the color when hovering. |
NoLabel |
Don't show the label (for inline color edits). |
NoSidePreview |
Don't show the large preview pane in the picker. |
NoDragDrop |
Disable drag-and-drop target/source. |
NoBorder |
Don't draw a border around the color square. |
AlphaBar |
Show a vertical alpha bar in the picker. |
AlphaPreview |
Half-checkered preview for alpha in the preview square. |
AlphaPreviewHalf |
Alpha preview only on the right half of the square. |
HDR |
Allow values above 1.0f (for HDR workflows). |
DisplayRGB |
Show RGB display. |
DisplayHSV |
Show HSV display. |
DisplayHex |
Show hex display. |
Uint8 |
Display values as 0–255 integers. |
Float |
Display values as 0.0–1.0 floats. |
PickerHueBar |
Use a hue bar in the color picker. |
PickerHueWheel |
Use a hue wheel in the color picker. |
InputRGB |
Input/output values in RGB format. |
InputHSV |
Input/output values in HSV format. |
ImGuiSliderFlags_
| Flag | Description |
|---|---|
Logarithmic |
Logarithmic slider scale (useful for very large ranges). |
NoRoundToFormat |
Disable rounding the value to the format string precision when Ctrl+clicking. |
NoInput |
Disable Ctrl+Click to enter a text value. |
WrapAround |
Slider wraps around min/max (for angle sliders, etc.). |
ClampOnInput |
Clamp keyboard/drag input to min/max. By default, Ctrl+Click text input can go beyond range. |
ClampZeroRange |
Clamp even if min == max. By default, when min == max, slider allows any value. |
NoSpeedTweaks |
Disable speed tweaks for Drag widgets (linear 1:1 mapping). |
ImGuiMultiSelectFlags_
| Flag | Description |
|---|---|
SingleSelect |
Single selection mode (disable multi-select). |
NoSelectAll |
Disable Ctrl+A to select all. |
NoRangeSelect |
Disable Shift+Click range selection. |
NoAutoSelect |
Don't auto-select a single item when navigation moves to it. |
NoAutoClear |
Don't clear selection when clicking on void. |
NoAutoClearOnReselect |
Don't clear selection when clicking an already-selected item. |
BoxSelect |
Enable box/lasso selection with mouse drag. |
BoxSelect2d |
Box selection works in 2D (not just 1D list). |
NavWrapX |
Keyboard navigation wraps horizontally within the multi-select area. |
ClearOnEscape |
Clear selection when pressing Escape. |
ScopeWindow |
Multi-select covers the whole window (not just until EndMultiSelect()). |
ScopeRect |
Multi-select covers a defined rectangular area. |
SelectOnClick |
Select on click, not on release. |
SelectOnClickRelease |
Select on click release (allows drag-and-drop of selected items). |
ImGuiButtonFlags_ (Public Subset)
| Flag | Description |
|---|---|
MouseButtonLeft |
React to left mouse button (default). |
MouseButtonRight |
React to right mouse button. |
MouseButtonMiddle |
React to middle mouse button. |
EnableNav |
This button can be activated via keyboard navigation (Enter/Space). |
ImDrawFlags_
| Flag | Description |
|---|---|
Closed |
AddPolyline(): close the shape by connecting the last point to the first. |
RoundCornersTopLeft |
Round the top-left corner. |
RoundCornersTopRight |
Round the top-right corner. |
RoundCornersBottomLeft |
Round the bottom-left corner. |
RoundCornersBottomRight |
Round the bottom-right corner. |
RoundCornersNone |
Don't round any corners. |
RoundCornersTop |
Round both top corners. |
RoundCornersBottom |
Round both bottom corners. |
RoundCornersLeft |
Round both left corners. |
RoundCornersRight |
Round both right corners. |
RoundCornersAll |
Round all corners (default when rounding > 0). |
ImDrawListFlags_
| Flag | Description |
|---|---|
AntiAliasedLines |
Enable anti-aliased line rendering. |
AntiAliasedLinesUseTex |
Use texture-based anti-aliasing for lines. |
AntiAliasedFill |
Enable anti-aliased fill for shapes. |
AllowVtxOffset |
Allow VtxOffset to be emitted (for large meshes). Requires renderer support. |
ImFontAtlasFlags_
| Flag | Description |
|---|---|
NoPowerOfTwoHeight |
Don't round the atlas texture height to the next power of two. |
NoMouseCursors |
Don't build software mouse cursor shapes into the atlas. |
NoBakedLines |
Don't build thick line textures into the atlas (disables AntiAliasedLinesUseTex). |
ImGuiCol_ (Color Identifiers)
| Enum Value | Description |
|---|---|
Text |
Default text color. |
TextDisabled |
Disabled/grayed-out text. |
WindowBg |
Window background. |
ChildBg |
Child window background. |
PopupBg |
Popup/tooltip/menu background. |
Border |
Borders. |
BorderShadow |
Border shadow (currently unused by default style). |
FrameBg |
Widget frame background (checkbox, slider, input). |
FrameBgHovered |
Widget frame background when hovered. |
FrameBgActive |
Widget frame background when active/pressed. |
TitleBg |
Title bar background. |
TitleBgActive |
Title bar background when the window is focused. |
TitleBgCollapsed |
Title bar background when collapsed. |
MenuBarBg |
Menu bar background. |
ScrollbarBg |
Scrollbar background. |
ScrollbarGrab |
Scrollbar grab handle. |
ScrollbarGrabHovered |
Scrollbar grab handle when hovered. |
ScrollbarGrabActive |
Scrollbar grab handle when held. |
CheckMark |
Checkbox/radio check mark. |
SliderGrab |
Slider grab handle. |
SliderGrabActive |
Slider grab handle when held. |
Button |
Button background. |
ButtonHovered |
Button background when hovered. |
ButtonActive |
Button background when pressed. |
Header |
Collapsing header / tree node / selectable / menu item background. |
HeaderHovered |
Same, when hovered. |
HeaderActive |
Same, when active/pressed. |
Separator |
Separator line. |
SeparatorHovered |
Separator when hovered (for resizable separators). |
SeparatorActive |
Separator when held. |
ResizeGrip |
Window resize grip (bottom-right corner). |
ResizeGripHovered |
Resize grip when hovered. |
ResizeGripActive |
Resize grip when held. |
TabHovered |
Tab when hovered. |
Tab |
Unselected tab. |
TabSelected |
Selected tab. |
TabSelectedOverline |
Overline on selected tab. |
TabDimmed |
Unfocused/dimmed tab. |
TabDimmedSelected |
Unfocused/dimmed selected tab. |
TabDimmedSelectedOverline |
Overline on unfocused selected tab. |
PlotLines |
PlotLines() line color. |
PlotLinesHovered |
PlotLines() hovered line segment. |
PlotHistogram |
PlotHistogram() bar color. |
PlotHistogramHovered |
PlotHistogram() hovered bar. |
TableHeaderBg |
Table header row background. |
TableBorderStrong |
Strong/outer table borders. |
TableBorderLight |
Light/inner table borders. |
TableRowBg |
Table row background (even rows). |
TableRowBgAlt |
Table row background (odd rows, alternating). |
TextLink |
Hyperlink text color. |
TextSelectedBg |
Selected text background color (e.g., in InputText). |
DragDropTarget |
Drop target highlight rectangle. |
NavCursor |
Navigation cursor/highlight rectangle. |
NavWindowingHighlight |
Window highlight for Ctrl+Tab window picker. |
NavWindowingDimBg |
Background dimming for Ctrl+Tab window picker. |
ModalWindowDimBg |
Background dimming for modal windows. |
ImGuiStyleVar_ (Style Variables for PushStyleVar)
| Enum Value | Type | Mapped To |
|---|---|---|
Alpha |
float |
style.Alpha |
DisabledAlpha |
float |
style.DisabledAlpha |
WindowPadding |
ImVec2 |
style.WindowPadding |
WindowRounding |
float |
style.WindowRounding |
WindowBorderSize |
float |
style.WindowBorderSize |
WindowMinSize |
ImVec2 |
style.WindowMinSize |
WindowTitleAlign |
ImVec2 |
style.WindowTitleAlign |
ChildRounding |
float |
style.ChildRounding |
ChildBorderSize |
float |
style.ChildBorderSize |
PopupRounding |
float |
style.PopupRounding |
PopupBorderSize |
float |
style.PopupBorderSize |
FramePadding |
ImVec2 |
style.FramePadding |
FrameRounding |
float |
style.FrameRounding |
FrameBorderSize |
float |
style.FrameBorderSize |
ItemSpacing |
ImVec2 |
style.ItemSpacing |
ItemInnerSpacing |
ImVec2 |
style.ItemInnerSpacing |
IndentSpacing |
float |
style.IndentSpacing |
CellPadding |
ImVec2 |
style.CellPadding |
ScrollbarSize |
float |
style.ScrollbarSize |
ScrollbarRounding |
float |
style.ScrollbarRounding |
GrabMinSize |
float |
style.GrabMinSize |
GrabRounding |
float |
style.GrabRounding |
TabRounding |
float |
style.TabRounding |
TabBorderSize |
float |
style.TabBorderSize |
TabBarBorderSize |
float |
style.TabBarBorderSize |
TabBarOverlineSize |
float |
style.TabBarOverlineSize |
ImageBorderSize |
float |
style.ImageBorderSize |
SeparatorTextBorderSize |
float |
style.SeparatorTextBorderSize |
SeparatorTextAlign |
ImVec2 |
style.SeparatorTextAlign |
SeparatorTextPadding |
ImVec2 |
style.SeparatorTextPadding |
ImGuiDir
| Value | Description |
|---|---|
None |
No direction. |
Left |
Left. |
Right |
Right. |
Up |
Up. |
Down |
Down. |
ImGuiMouseButton_
| Value | Description |
|---|---|
Left |
Left mouse button (index 0). |
Right |
Right mouse button (index 1). |
Middle |
Middle mouse button (index 2). |
ImGuiMouseCursor_
| Value | Description |
|---|---|
None |
No cursor (hidden). |
Arrow |
Default arrow cursor. |
TextInput |
I-beam cursor for text input. |
ResizeAll |
Four-way resize cursor (unused by Dear ImGui internally). |
ResizeNS |
Vertical resize cursor. |
ResizeEW |
Horizontal resize cursor. |
ResizeNESW |
Diagonal resize cursor (NE-SW). |
ResizeNWSE |
Diagonal resize cursor (NW-SE). |
Hand |
Hand/pointer cursor (for links). |
NotAllowed |
Not-allowed/unavailable cursor. |
ImGuiMouseSource
| Value | Description |
|---|---|
Mouse |
Input from a physical mouse. |
TouchScreen |
Input from a touchscreen. |
Pen |
Input from a pen/stylus. |
ImGuiCond_
| Value | Description |
|---|---|
Always |
Apply the value every frame. |
Once |
Apply the value the first time the item is used (per runtime session). |
FirstUseEver |
Apply the value the first time the item is used (persists across .ini sessions). |
Appearing |
Apply the value each time the window/item appears (transitions from hidden to visible). |
ImGuiDataType_
| Value | Description |
|---|---|
S8 |
Signed 8-bit integer. |
U8 |
Unsigned 8-bit integer. |
S16 |
Signed 16-bit integer. |
U16 |
Unsigned 16-bit integer. |
S32 |
Signed 32-bit integer (int). |
U32 |
Unsigned 32-bit integer. |
S64 |
Signed 64-bit integer. |
U64 |
Unsigned 64-bit integer. |
Float |
32-bit floating point. |
Double |
64-bit floating point. |
Bool |
Boolean. |
ImGuiSortDirection
| Value | Description |
|---|---|
None |
No sort direction. |
Ascending |
Ascending sort (A-Z, 0-9). |
Descending |
Descending sort (Z-A, 9-0). |
ImGuiKey (Selected Navigation/Interaction Keys)
The ImGuiKey enum contains entries for every keyboard key, gamepad input, and mouse button. Keys include:
- Keyboard:
ImGuiKey_Tab,ImGuiKey_LeftArrow,ImGuiKey_RightArrow,ImGuiKey_UpArrow,ImGuiKey_DownArrow,ImGuiKey_PageUp,ImGuiKey_PageDown,ImGuiKey_Home,ImGuiKey_End,ImGuiKey_Insert,ImGuiKey_Delete,ImGuiKey_Backspace,ImGuiKey_Space,ImGuiKey_Enter,ImGuiKey_Escape,ImGuiKey_AthroughImGuiKey_Z,ImGuiKey_0throughImGuiKey_9,ImGuiKey_F1throughImGuiKey_F24, function keys, modifier keys (LeftCtrl,LeftShift,LeftAlt,LeftSuper, and right-side variants). - Gamepad:
ImGuiKey_GamepadStart,ImGuiKey_GamepadBack,ImGuiKey_GamepadFaceLeft/Right/Up/Down,ImGuiKey_GamepadDpadLeft/Right/Up/Down,ImGuiKey_GamepadL1/R1/L2/R2/L3/R3,ImGuiKey_GamepadLStickLeft/Right/Up/Down,ImGuiKey_GamepadRStickLeft/Right/Up/Down. - Mouse:
ImGuiKey_MouseLeft,ImGuiKey_MouseRight,ImGuiKey_MouseMiddle,ImGuiKey_MouseX1,ImGuiKey_MouseX2,ImGuiKey_MouseWheelX,ImGuiKey_MouseWheelY. - Modifiers:
ImGuiMod_Ctrl,ImGuiMod_Shift,ImGuiMod_Alt,ImGuiMod_Super,ImGuiMod_Mask_(all modifiers).
4. Deployment & Scaling
Building Dear ImGui
Dear ImGui does not ship a build system. Integration is manual and deliberate:
- Copy the core source files into your project (or add as a submodule/subtree).
- Add the following to your compilation:
imgui.cppimgui_draw.cppimgui_tables.cppimgui_widgets.cppimgui_demo.cpp(optional, recommended for development)- Your chosen backend files (e.g.,
backends/imgui_impl_glfw.cpp+backends/imgui_impl_opengl3.cpp)
- Ensure the root directory and
backends/directory are in your include path. - Build and link. No special flags required beyond C++11.
Platform-Specific Notes
Windows (Visual Studio)
Pre-built Visual Studio solution files are provided in examples/ for several backend combinations:
example_win32_directx9/example_win32_directx10/example_win32_directx11/example_win32_directx12/example_win32_opengl3/example_glfw_opengl3/example_glfw_vulkan/example_sdl2_opengl3/example_sdl2_vulkan/example_sdl3_opengl3/example_sdl3_vulkan/example_sdl3_sdlgpu3/example_sdl3_sdlrenderer3/
MinGW is supported via the GNUmakefile in each example directory. For DLL builds, define IMGUI_API appropriately in imconfig.h.
Linux
Each example directory contains a Makefile for GCC/Clang. Install backend dependencies via your package manager:
# For GLFW + OpenGL3 example (Debian/Ubuntu)
apt-get install libglfw3-dev libgl1-mesa-dev
# For SDL2 + OpenGL3 example
apt-get install libsdl2-dev libgl1-mesa-dev
# For SDL3 examples (build SDL3 from source)
macOS
Xcode projects are provided for:
example_apple_metal/— Metal renderer with AppKit/UIKitexample_apple_opengl2/— Legacy OpenGL with GLUTexample_glfw_metal/— GLFW platform + Metal renderer
GLFW and SDL can be installed via Homebrew (brew install glfw, brew install sdl2).
Android
The example_android_opengl3/ directory contains a complete Android Studio project with Gradle and CMake integration. It uses the Android NDK's native activity and OpenGL ES 3.
Emscripten / WebAssembly
Several examples include Makefile.emscripten for building with Emscripten:
example_emscripten_wgpu/— WebGPU renderer (recommended for web)example_glfw_opengl3/— OpenGL3 via Emscripten's GLFW portexample_sdl2_opengl3/— OpenGL3 via Emscripten's SDL2 port
iOS
The example_apple_metal/ example supports both macOS and iOS targets via a shared Xcode project.
Single-File Build
For projects that prefer a single compilation unit, misc/single_file/imgui_single_file.h includes all core .cpp files:
// In exactly ONE .cpp file:
#include "imgui_single_file.h"
This compiles all of Dear ImGui in a single translation unit, which can improve compile times and enable better inlining.
DLL / Shared Library
Warning
Using Dear ImGui as a shared library (DLL) is possible but introduces complexity at every DLL boundary. Each DLL that calls Dear ImGui functions must share the same
ImGuiContextand memory allocators. This is NOT the default behavior on most platforms. Mishandling this causes crashes, memory corruption, and hard-to-diagnose bugs. If possible, statically link Dear ImGui into your application instead.
If you must use Dear ImGui across DLL boundaries:
- Define
IMGUI_APIas__declspec(dllexport)when building the DLL and__declspec(dllimport)when consuming it. - In every DLL that uses Dear ImGui, call
ImGui::SetCurrentContext()with the context from the host application. - Call
ImGui::SetAllocatorFunctions()with the same allocator functions in each DLL, before any other Dear ImGui call. - Alternatively, compile Dear ImGui into each DLL and share context manually.
Console Platforms
Dear ImGui is designed to work on consoles (PlayStation, Xbox, Nintendo Switch). The rendering model (textured triangles with clip rectangles) maps directly to console graphics APIs. Console backends are typically proprietary and maintained by the console developer community. The core library has no platform-specific requirements that prevent console deployment.
Integration Checklist
The following checklist covers the minimum steps to integrate Dear ImGui into an existing application:
[ ] Copy imgui source files into your project tree
[ ] Add imgui.cpp, imgui_draw.cpp, imgui_tables.cpp, imgui_widgets.cpp to your build
[ ] Add imgui_demo.cpp to your build (recommended for development)
[ ] Choose and add a platform backend (e.g., imgui_impl_glfw.cpp)
[ ] Choose and add a renderer backend (e.g., imgui_impl_opengl3.cpp)
[ ] Add imgui/ and imgui/backends/ to your include path
[ ] In your init code: call ImGui::CreateContext()
[ ] In your init code: configure ImGuiIO (ConfigFlags, fonts, etc.)
[ ] In your init code: call backend Init functions
[ ] In your init code: build and upload the font atlas texture
[ ] In your main loop: call backend NewFrame functions
[ ] In your main loop: call ImGui::NewFrame()
[ ] In your main loop: call your UI code (Begin/End, widgets, etc.)
[ ] In your main loop: call ImGui::Render()
[ ] In your main loop: call backend RenderDrawData function
[ ] In your shutdown code: call backend Shutdown functions
[ ] In your shutdown code: call ImGui::DestroyContext()
Minimal Integration Example
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include <GLFW/glfw3.h>
int main() {
// Platform init
glfwInit();
GLFWwindow* window = glfwCreateWindow(1280, 720, "My App", NULL, NULL);
glfwMakeContextCurrent(window);
// Dear ImGui init
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
// Backend init
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init("#version 130");
// Main loop
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
// Your UI code
ImGui::ShowDemoWindow();
// Render
ImGui::Render();
int display_w, display_h;
glfwGetFramebufferSize(window, &display_w, &display_h);
glViewport(0, 0, display_w, display_h);
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(window);
}
// Shutdown
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
Upgrading Between Versions
When upgrading Dear ImGui to a new version:
- Read the relevant section of
docs/CHANGELOG.txtfor breaking changes. - Compile with
IMGUI_DISABLE_OBSOLETE_FUNCTIONStemporarily defined to identify deprecated API usage. - Update backend files — they must match the core version.
- Delete
imgui.iniif the layout looks broken (settings format may have changed subtly). - Test with the demo window (
ShowDemoWindow()) to verify rendering correctness.
Important
Always update the core library files and backend files together. Mixing core files from one version with backend files from another version causes subtle bugs, crashes, or compilation errors. The
IMGUI_CHECKVERSION()macro helps detect version mismatches at runtime.
5. Operations
5.1 Settings Persistence (.ini)
Dear ImGui automatically saves and loads UI layout settings to a .ini file. This includes window positions, sizes, collapsed states, and table column configuration (widths, order, visibility, sort state).
Configuration
| Setting | Value | Behavior |
|---|---|---|
io.IniFilename = "imgui.ini" |
Default path | Auto-load on CreateContext(), auto-save on DestroyContext() and periodically. |
io.IniFilename = "path/to/custom.ini" |
Custom path | Same behavior, custom file location. |
io.IniFilename = NULL |
Disabled | No automatic loading or saving. You manage persistence manually. |
Manual Save/Load
// Save to disk
ImGui::SaveIniSettingsToDisk("imgui.ini");
// Save to memory (returns a string you can store however you like)
const char* ini_data = ImGui::SaveIniSettingsToMemory();
// Load from disk
ImGui::LoadIniSettingsFromDisk("imgui.ini");
// Load from memory buffer
ImGui::LoadIniSettingsFromMemory(ini_data, ini_data_size);
Custom Save Timing
Check io.WantSaveIniSettings each frame. When true, Dear ImGui wants to persist settings. You can save at that moment and clear the flag:
if (io.WantSaveIniSettings) {
const char* data = ImGui::SaveIniSettingsToMemory();
// Write 'data' to your custom storage (database, cloud, etc.)
io.WantSaveIniSettings = false;
}
What Gets Stored
- Window state: Position, size, collapsed/expanded, scroll position
- Table state: Column widths, column order, column visibility, sort column and direction
- Settings handlers: Custom data via
ImGuiSettingsHandler(register withImGui::AddSettingsHandler())
5.2 Debug Tools
Dear ImGui ships several built-in debug tools for inspecting internal state:
Metrics/Debugger Window
ImGui::ShowMetricsWindow(&show_metrics);
Tip
The Metrics window is the single most useful debugging tool in Dear ImGui. It shows windows, draw commands, font atlas contents, active IDs, internal state, and memory usage. When something looks wrong, open Metrics first.
Features:
- Window list with geometry, flags, draw command counts
- Draw command list per window (texture, vertex count, clip rect)
- Font atlas visualization
- Active ID / hovered ID display
- Input event log
- Internal state inspection
Debug Log Window
ImGui::ShowDebugLogWindow(&show_debug_log);
Displays a simplified event log of internal Dear ImGui events (focus changes, activation, navigation, etc.). Use io.ConfigDebugHighlightIdConflicts to detect and surface duplicate ID issues.
ID Stack Tool
ImGui::ShowIDStackToolWindow(&show_id_stack);
Hover any item to see the full ID stack that produced its unique identifier. Invaluable for diagnosing ID conflicts, which manifest as widgets sharing state (e.g., two sliders that move together).
About Window
ImGui::ShowAboutWindow(&show_about);
Shows version information, build configuration, credits, and compile-time options that are active.
Item Picker
ImGui::DebugStartItemPicker();
Activates a mode where you can click any widget to select it in the Metrics window. Useful for finding which code created a specific visual element.
Style Color Flash
ImGui::DebugFlashStyleColor(ImGuiCol_Button);
Briefly flashes all widgets using the specified color, helping you identify which elements use which style colors.
Compile-Time Debug Options
IMGUI_DEBUG_PARANOID— Enable slower, stricter assertions. For CI/development builds.IMGUI_DEBUG_HIGHLIGHT_ALL_ID_CONFLICTS— Highlight every conflicting ID (not just the first pair). Performance impact.
5.3 Logging / Capture
Dear ImGui can capture all text output from widgets to a file, the clipboard, or TTY:
// Start logging
ImGui::LogToTTY(); // Log to stdout
ImGui::LogToFile(-1, "log.txt"); // Log to file
ImGui::LogToClipboard(); // Log to OS clipboard
// ... render widgets (their text output is captured) ...
// Stop logging
ImGui::LogFinish();
// Show log buttons in the UI
ImGui::LogButtons(); // Renders Log To TTY / File / Clipboard buttons
// Insert custom text into the log
ImGui::LogText("Custom log entry\n");
Logging captures the text content of all widgets rendered between LogTo*() and LogFinish(). This is useful for generating text summaries of UI state or for accessibility.
6. Performance
Draw Call Batching
Dear ImGui automatically batches draw calls by texture. All widgets rendered with the same texture (typically the font atlas) are merged into continuous vertex/index buffers with a single draw command. Texture changes or clip rectangle changes create new draw commands.
The number of draw commands per frame is visible in the Metrics window. Typical applications with a single font produce very few draw commands (often single digits).
Note
Dear ImGui's rendering is NOT immediate-mode at the GPU level. Despite the immediate-mode API, Dear ImGui accumulates geometry into optimized vertex buffers that are rendered in batched draw calls. This is comparable to retained-mode rendering performance for the same geometry.
Large List Optimization with ImGuiListClipper
For lists with thousands or millions of items, ImGuiListClipper performs viewport culling — only items visible on screen are processed:
ImGuiListClipper clipper;
clipper.Begin(1000000); // 1 million items
while (clipper.Step()) {
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) {
ImGui::Text("Item %d", i);
}
}
This reduces per-frame cost from O(N) to O(visible items), regardless of total count.
Index Buffer Size
By default, ImDrawIdx is unsigned short (16-bit), limiting each ImDrawList to 65535 vertices. For complex UIs that exceed this:
- Recommended: Define
ImDrawIdxasunsigned intinimconfig.hfor 32-bit indices. - Alternative: Enable
ImGuiBackendFlags_RendererHasVtxOffsetin your renderer to support theImDrawCmd::VtxOffsetfield, which allows 16-bit indices with vertex offsets.
Anti-Aliasing Controls
| Setting | Impact | Trade-off |
|---|---|---|
AntiAliasedLines = false |
Reduces vertex count for lines | Jagged lines |
AntiAliasedLinesUseTex = false |
Falls back to geometric AA | Slightly slower AA, but works without bilinear filtering |
AntiAliasedFill = false |
Reduces vertex count for shapes | Jagged edges on rounded shapes |
CurveTessellationTol (higher) |
Fewer vertices for curves | Coarser curves |
CircleTessellationMaxError (higher) |
Fewer vertices for circles | More angular circles |
SSE Optimizations
SSE intrinsics are used for ImVec2/ImVec4 operations when available (x86/x64, MSVC/GCC/Clang). Disable with IMGUI_DISABLE_SSE if targeting non-SSE platforms or if conflicts arise.
Memory Management
Dear ImGui uses a pluggable allocator system:
// Set custom allocators BEFORE CreateContext()
ImGui::SetAllocatorFunctions(MyMallocFunc, MyFreeFunc, my_user_data);
ImGui::CreateContext();
All internal allocations go through these functions. The default uses malloc/free. Custom allocators can integrate with your engine's memory system, track allocations, or use pool allocators for reduced fragmentation.
Text Rendering
For large text blocks, use TextUnformatted() instead of Text():
// Slow for large text: copies and formats the string
ImGui::Text("%s", large_buffer);
// Fast for large text: no copy, no formatting, direct rendering
ImGui::TextUnformatted(large_buffer, large_buffer + large_buffer_size);
TextUnformatted() accepts a begin/end pointer pair and renders directly without copying or formatting. For multi-megabyte text blocks, this is significantly faster.
Font Atlas Optimization
The font atlas texture size directly impacts GPU memory and upload time. Optimize by:
| Strategy | Impact |
|---|---|
| Load only needed glyph ranges | Smaller atlas, faster build |
Use ImFontAtlasFlags_NoPowerOfTwoHeight |
Avoid wasting up to 50% height |
Use ImFontAtlasFlags_NoMouseCursors |
Save space if using hardware cursors |
Use ImFontAtlasFlags_NoBakedLines |
Save space if AntiAliasedLinesUseTex is disabled |
Merge fonts with MergeMode |
Combine icon fonts into the main font to reduce texture switches |
| Use FreeType with SDF rendering | Better scaling without multiple atlas sizes |
Performance Profiling
Use the Metrics window (ShowMetricsWindow()) to monitor:
- Draw commands per frame: Should be low (single digits for simple UIs, tens for complex ones)
- Vertices/indices per frame: Thousands is normal; hundreds of thousands suggests optimization opportunities
- Window count: Hidden windows still consume memory; use
NoSavedSettingsfor transient windows - Font atlas size: Monitor texture dimensions; consider glyph range reduction if oversized
Threading Considerations
Dear ImGui is NOT thread-safe. All calls must happen on a single thread (the thread that calls NewFrame() and Render()). Common safe patterns:
- Collect data from worker threads into shared buffers, then display from the main thread
- Use
ImGui::SetCurrentContext()if different threads use different contexts (rare) - The
ImDrawListsplitter (ImDrawListSplitter) can help organize draw data but does not enable multi-threaded submission
7. Security
Dear ImGui is a client-side UI library with a minimal attack surface. It does not open network connections, parse untrusted input formats, or manage credentials. Security considerations are primarily about integration safety.
File System Access
By default, Dear ImGui performs file I/O only for:
- Settings: Loading/saving
imgui.ini(controlled byio.IniFilename) - Logging: Writing to
io.LogFilenamewhen logging is active - Shell: Opening files/URLs via
Platform_OpenInShellFn
To fully disable file I/O:
// In imconfig.h
#define IMGUI_DISABLE_FILE_FUNCTIONS // Removes ALL file I/O, including .ini
To disable only shell execution:
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
Memory Safety
- All assertions are configurable via
IM_ASSERT. Override to integrate with your crash reporting. - Buffer sizes for
InputTextare caller-controlled. Dear ImGui respects the provided buffer size. ImVector(internal dynamic array) uses bounds checking in debug builds.
Input Validation
Dear ImGui uses IM_ASSERT extensively to catch programmer errors (null pointers, mismatched Begin/End calls, invalid parameters). These are development-time checks, not security validations. In release builds, IM_ASSERT typically compiles to nothing.
Caution
When using Dear ImGui across DLL boundaries, you MUST call
ImGui::SetCurrentContext()andImGui::SetAllocatorFunctions()in every DLL before making any Dear ImGui calls. Failure to do this causes memory corruption: one DLL allocates with its own heap, another DLL frees from a different heap. This is the most common source of crashes in DLL-based Dear ImGui deployments.
No Secrets Handling
Dear ImGui does not process, store, or transmit credentials, tokens, or sensitive data. The InputText widget with ImGuiInputTextFlags_Password masks display characters but stores the plaintext in the caller's buffer — Dear ImGui does not manage that buffer's lifetime or security.
Anti-Cheat Considerations
The CONTRIBUTING.md file explicitly states that Dear ImGui does not accept contributions related to cheating in online games. While Dear ImGui is commonly used for game development tools and debug overlays, using it to create cheat interfaces for online games is outside the project's intended use and community norms.
8. Developer Internals
8.1 Repository Structure
imgui/
├── imgui.cpp Core library (~22K lines)
├── imgui.h Public API header
├── imgui_internal.h Internal types (not public API)
├── imgui_widgets.cpp All standard widgets
├── imgui_tables.cpp Table system
├── imgui_draw.cpp Drawing, font atlas, textures
├── imgui_demo.cpp Demo window with inline code samples
├── imconfig.h Compile-time configuration
├── imstb_rectpack.h Embedded stb_rect_pack
├── imstb_textedit.h Embedded stb_textedit
├── imstb_truetype.h Embedded stb_truetype
├── backends/ Platform + renderer backends
│ ├── imgui_impl_glfw.cpp/h GLFW platform backend
│ ├── imgui_impl_sdl2.cpp/h SDL2 platform backend
│ ├── imgui_impl_sdl3.cpp/h SDL3 platform backend
│ ├── imgui_impl_win32.cpp/h Win32 platform backend
│ ├── imgui_impl_osx.mm/h macOS/Cocoa platform backend
│ ├── imgui_impl_android.cpp/h Android platform backend
│ ├── imgui_impl_glut.cpp/h GLUT platform backend (legacy)
│ ├── imgui_impl_opengl2.cpp/h OpenGL2 renderer backend
│ ├── imgui_impl_opengl3.cpp/h OpenGL3/ES2/ES3 renderer backend
│ ├── imgui_impl_opengl3_loader.h Minimal OpenGL function loader
│ ├── imgui_impl_dx9.cpp/h DirectX9 renderer backend
│ ├── imgui_impl_dx10.cpp/h DirectX10 renderer backend
│ ├── imgui_impl_dx11.cpp/h DirectX11 renderer backend
│ ├── imgui_impl_dx12.cpp/h DirectX12 renderer backend
│ ├── imgui_impl_vulkan.cpp/h Vulkan renderer backend
│ ├── imgui_impl_metal.mm/h Metal renderer backend
│ ├── imgui_impl_wgpu.cpp/h WebGPU renderer backend
│ ├── imgui_impl_sdlgpu3.cpp/h SDL_GPU renderer backend
│ ├── imgui_impl_sdlrenderer2.cpp/h SDL_Renderer2 renderer backend
│ ├── imgui_impl_sdlrenderer3.cpp/h SDL_Renderer3 renderer backend
│ ├── imgui_impl_allegro5.cpp/h Allegro5 combined backend
│ ├── imgui_impl_null.cpp/h Null/no-op backend (for testing)
│ ├── vulkan/ GLSL shaders + SPIR-V for Vulkan
│ └── sdlgpu3/ Shaders for SDL_GPU backend
├── examples/ 26 example applications
│ ├── example_win32_directx9/
│ ├── example_win32_directx10/
│ ├── example_win32_directx11/
│ ├── example_win32_directx12/
│ ├── example_win32_opengl3/
│ ├── example_glfw_opengl2/
│ ├── example_glfw_opengl3/
│ ├── example_glfw_vulkan/
│ ├── example_glfw_metal/
│ ├── example_sdl2_opengl2/
│ ├── example_sdl2_opengl3/
│ ├── example_sdl2_vulkan/
│ ├── example_sdl2_sdlrenderer2/
│ ├── example_sdl3_opengl3/
│ ├── example_sdl3_vulkan/
│ ├── example_sdl3_sdlgpu3/
│ ├── example_sdl3_sdlrenderer3/
│ ├── example_apple_metal/
│ ├── example_apple_opengl2/
│ ├── example_android_opengl3/
│ ├── example_emscripten_wgpu/
│ ├── example_allegro5/
│ ├── example_glut_opengl2/
│ └── example_null/
├── misc/
│ ├── cpp/ std::string InputText helpers
│ │ ├── imgui_stdlib.cpp
│ │ └── imgui_stdlib.h
│ ├── debuggers/ IDE/debugger helpers
│ │ ├── imgui.natvis Visual Studio type visualization
│ │ ├── imgui.natstepfilter Visual Studio step filter
│ │ ├── imgui.gdb GDB pretty printers
│ │ └── imgui_lldb.py LLDB synthetic children
│ ├── fonts/ Bundled TTF fonts (7 fonts)
│ ├── freetype/ FreeType font rasterizer integration
│ │ └── imgui_freetype.cpp/h
│ └── single_file/ Single-compilation-unit header
│ └── imgui_single_file.h
└── docs/ Documentation
├── FAQ.md
├── BACKENDS.md
├── FONTS.md
├── CHANGELOG.txt
├── EXAMPLES.md
├── README.md
├── TODO.txt
└── CONTRIBUTING.md
8.2 Architecture Deep Dive
ImGuiContext
ImGuiContext is the central state container. Everything Dear ImGui knows is stored here: the window list, IO state, style, font atlas, navigation state, settings, active widget IDs, drag-and-drop state, and more. A global pointer (GImGui) points to the current context.
// Create and set context (typically once at startup)
ImGuiContext* ctx = ImGui::CreateContext();
// Multiple contexts are supported (e.g., for testing)
ImGuiContext* ctx2 = ImGui::CreateContext();
ImGui::SetCurrentContext(ctx2); // Switch active context
Multiple contexts are independent — each has its own windows, fonts, style, and state. This is used for unit testing, editor-within-editor scenarios, or DLL boundary management.
Window System
Windows (ImGuiWindow) are created and managed internally. Each ImGui::Begin("Name") call finds or creates a window identified by the hash of its name string. Windows store:
- Position, size, scroll position
- Draw list (
ImDrawList) - Content region and work rect
- Collapsed/skipped state
- Parent/child relationships
Window ordering (front-to-back) is managed by the focus system. BringToFront operations are deferred to avoid reordering during iteration.
ID System
Dear ImGui uses a stack-based hashing system to generate unique IDs for widgets. Each widget needs a unique ID to maintain its state (active, focused, edited value, etc.) across frames.
// ID is hash of "##MySlider" + window ID
ImGui::SliderFloat("##MySlider", &value, 0.0f, 1.0f);
// Push additional ID components onto the stack
ImGui::PushID(item_index);
ImGui::Button("OK"); // ID = window + item_index + "OK"
ImGui::PopID();
// String IDs
ImGui::PushID("subsection");
ImGui::Button("OK"); // ID = window + "subsection" + "OK"
ImGui::PopID();
ID conflicts (two widgets with the same ID) cause them to share state — sliders move together, buttons activate together. Use the ID Stack Tool (ShowIDStackToolWindow()) and io.ConfigDebugHighlightIdConflicts to detect these issues.
ImDrawList
ImDrawList is the low-level drawing API. Each window has one. It accumulates draw commands as vertex/index buffers:
- Primitives:
AddLine(),AddRect(),AddRectFilled(),AddCircle(),AddCircleFilled(),AddTriangle(),AddTriangleFilled() - Complex shapes:
AddBezierCubic(),AddBezierQuadratic(),AddPolyline(),AddConvexPolyFilled(),AddConcavePolyFilled() - Text:
AddText() - Images:
AddImage(),AddImageQuad(),AddImageRounded() - Clipping:
PushClipRect(),PopClipRect()
You can also obtain a foreground or background ImDrawList via ImGui::GetForegroundDrawList() / ImGui::GetBackgroundDrawList() for drawing outside of window boundaries.
ImDrawData
After ImGui::Render(), ImGui::GetDrawData() returns an ImDrawData struct containing:
CmdLists[]— Array ofImDrawListpointersTotalVtxCount,TotalIdxCount— Total vertex/index countDisplayPos,DisplaySize— Viewport coordinatesFramebufferScale— For high-DPI rendering
The renderer backend iterates CmdLists, then iterates each list's CmdBuffer (array of ImDrawCmd), setting up clip rectangles and textures, and issuing draw calls.
ImFontAtlas
ImFontAtlas manages font loading, glyph rasterization, and texture atlas packing:
ImGuiIO& io = ImGui::GetIO();
// Add fonts
io.Fonts->AddFontDefault(); // ProggyClean 13px
io.Fonts->AddFontFromFileTTF("Roboto-Medium.ttf", 16.0f); // Custom font
io.Fonts->AddFontFromFileTTF("icons.ttf", 16.0f, &config, icon_ranges); // Icon font
// Build the atlas (called automatically, or manually)
io.Fonts->Build();
// Get texture data for upload to GPU
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// Upload 'pixels' to your GPU texture...
In v1.92+, the font atlas supports dynamic rebuilding and the ImTextureData / ImTextureRef system for decoupling texture identity from GPU upload timing.
Navigation System
Dear ImGui includes a complete keyboard/gamepad navigation system. When enabled via ImGuiConfigFlags_NavEnableKeyboard or ImGuiConfigFlags_NavEnableGamepad:
- Arrow keys move focus between widgets
- Enter/Space activate the focused widget
- Alt activates menu bars
- Escape closes popups/menus
- Ctrl+Tab switches between windows
The navigation system handles focus scoping, shortcut routing (ensuring the correct widget receives a keyboard shortcut), and input ownership (which subsystem "owns" a particular key press this frame).
Settings System
The settings system persists and restores UI state across sessions. Built-in handlers save window and table state. Custom handlers can be registered:
ImGuiSettingsHandler handler;
handler.TypeName = "MyData";
handler.TypeHash = ImHashStr("MyData");
handler.ReadOpenFn = MyReadOpenFn;
handler.ReadLineFn = MyReadLineFn;
handler.WriteAllFn = MyWriteAllFn;
ImGui::AddSettingsHandler(&handler);
8.3 Backend Interface
Writing a Custom Platform Backend
A platform backend feeds Dear ImGui with OS-level information. Implement these responsibilities:
Required:
- Set
io.DisplaySizeevery frame with the window/framebuffer dimensions. - Set
io.DeltaTimeevery frame with the elapsed time since last frame. - Feed keyboard input via
io.AddKeyEvent(),io.AddKeyAnalogEvent(). - Feed mouse input via
io.AddMousePosEvent(),io.AddMouseButtonEvent(),io.AddMouseWheelEvent(). - Set
io.AddFocusEvent()when the application window gains/loses focus.
Optional:
6. Set io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors and implement cursor shape changes via ImGui::GetMouseCursor().
7. Set io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos if you can reposition the OS mouse.
8. Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad and feed gamepad input.
9. Implement platform_io.Platform_GetClipboardTextFn / Platform_SetClipboardTextFn for clipboard.
10. Implement platform_io.Platform_SetImeDataFn for IME support.
11. Implement platform_io.Platform_OpenInShellFn for opening files/URLs.
Writing a Custom Renderer Backend
A renderer backend creates GPU resources and draws the geometry Dear ImGui produces.
Required:
- Create a GPU texture from the font atlas pixel data (
io.Fonts->GetTexDataAsRGBA32()). - Store the GPU texture handle in
io.Fonts->SetTexID(). - Implement the render loop: iterate
ImDrawData->CmdLists[], set up an orthographic projection, and for eachImDrawCmd:- Set the clip/scissor rectangle from
cmd.ClipRect - Bind the texture from
cmd.GetTexID() - Draw
cmd.ElemCountindices starting atcmd.IdxOffsetwith vertex offsetcmd.VtxOffset
- Set the clip/scissor rectangle from
- Handle the special
ImDrawCallbackvalues: ifcmd.UserCallback == ImDrawCallback_ResetRenderState, reset your render state.
Note
The
platform_io.Textures[]system (new in v1.92) provides a backend-agnostic way to manage textures dynamically. WhenImGuiBackendFlags_RendererHasTexturesis set, Dear ImGui createsImTextureDataentries inplatform_io.Textures[]that the renderer should process (upload new textures, update changed ones, destroy removed ones) each frame. This enables dynamic font atlas rebuilding without application-level intervention.
Optional:
5. Set io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset if your renderer supports ImDrawCmd::VtxOffset (required for large meshes with 16-bit indices).
6. Handle ImDrawCallback_SetSamplerLinear and ImDrawCallback_SetSamplerNearest for texture filtering control.
7. Set io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures and process platform_io.Textures[] for dynamic texture management.
8.4 Official Backends Inventory
Platform Backends
| Backend | File | Input | Clipboard | Cursor | IME | Gamepad | Notes |
|---|---|---|---|---|---|---|---|
| GLFW | imgui_impl_glfw.cpp/h |
Yes | Yes | Yes | Yes | Yes | Cross-platform, widely used |
| SDL2 | imgui_impl_sdl2.cpp/h |
Yes | Yes | Yes | Yes | Yes | Mature, cross-platform |
| SDL3 | imgui_impl_sdl3.cpp/h |
Yes | Yes | Yes | Yes | Yes | Latest SDL |
| Win32 | imgui_impl_win32.cpp/h |
Yes | Yes | Yes | Yes | Yes (XInput) | Native Windows, no dependencies |
| OSX | imgui_impl_osx.mm/h |
Yes | Yes | Yes | — | — | Cocoa/AppKit native |
| Android | imgui_impl_android.cpp/h |
Touch + KB | — | — | — | — | Android native activity |
| GLUT | imgui_impl_glut.cpp/h |
Partial | — | — | — | — | Legacy, not recommended for new projects |
Renderer Backends
| Backend | File | VtxOffset | Textures API | Sampler Callbacks | Notes |
|---|---|---|---|---|---|
| OpenGL2 | imgui_impl_opengl2.cpp/h |
No | No | No | Legacy fixed-function pipeline |
| OpenGL3 | imgui_impl_opengl3.cpp/h |
Yes | Yes | Yes | Programmable pipeline, includes its own GL loader |
| DirectX9 | imgui_impl_dx9.cpp/h |
No | No | No | Legacy, widely compatible |
| DirectX10 | imgui_impl_dx10.cpp/h |
Yes | Yes | Yes | — |
| DirectX11 | imgui_impl_dx11.cpp/h |
Yes | Yes | Yes | Most common choice for Windows |
| DirectX12 | imgui_impl_dx12.cpp/h |
Yes | Yes | Yes | Requires more setup (descriptor heaps, command lists) |
| Vulkan | imgui_impl_vulkan.cpp/h |
Yes | Yes | Yes | GLSL shaders in backends/vulkan/ |
| Metal | imgui_impl_metal.mm/h |
Yes | Yes | Yes | macOS/iOS native |
| WebGPU | imgui_impl_wgpu.cpp/h |
Yes | Yes | Yes | Browser/Dawn/wgpu-native |
| SDL_GPU | imgui_impl_sdlgpu3.cpp/h |
Yes | Yes | Yes | SDL3's GPU abstraction, shaders in backends/sdlgpu3/ |
| SDL_Renderer2 | imgui_impl_sdlrenderer2.cpp/h |
No | No | No | SDL2's 2D renderer |
| SDL_Renderer3 | imgui_impl_sdlrenderer3.cpp/h |
No | No | No | SDL3's 2D renderer |
Combined Backends
| Backend | File | Notes |
|---|---|---|
| Allegro5 | imgui_impl_allegro5.cpp/h |
Handles both platform input and rendering |
| Null | imgui_impl_null.cpp/h |
No-op backend for headless testing and CI |
8.5 Module Reference
imgui.cpp (~22,000 lines)
The core module. Implements:
- Context management:
CreateContext(),DestroyContext(),SetCurrentContext(),GetCurrentContext() - Frame lifecycle:
NewFrame(),EndFrame(),Render(),GetDrawData() - Window system:
Begin(),End(), window creation/destruction, ordering, focus management - ID system:
PushID(),PopID(),GetID(), the hash stack - Layout: cursor positioning,
SameLine(),NewLine(),Separator(),Spacing(),Dummy(),Indent(),Unindent(),Group - Input processing: mouse, keyboard, gamepad event queue, input ownership, focus routing
- Navigation: keyboard/gamepad focus movement, shortcut routing,
SetKeyboardFocusHere() - Popups & modals:
OpenPopup(),BeginPopup(),BeginPopupModal(),CloseCurrentPopup(), popup stack management - Drag-and-drop:
BeginDragDropSource(),SetDragDropPayload(),BeginDragDropTarget(),AcceptDragDropPayload() - Settings: .ini load/save,
ImGuiSettingsHandlerregistration - Miscellaneous:
IsItemHovered(),IsItemActive(),IsItemClicked(),SetTooltip(),BeginTooltip(), color conversion, clipboard, style management
imgui_widgets.cpp
All user-facing widgets:
- Text:
Text(),TextColored(),TextWrapped(),TextUnformatted(),BulletText(),SeparatorText(),TextLink(),TextLinkOpenURL() - Buttons:
Button(),SmallButton(),InvisibleButton(),ArrowButton(),ImageButton() - Checkboxes & radio:
Checkbox(),CheckboxFlags(),RadioButton() - Sliders:
SliderFloat(),SliderInt(),SliderAngle(),SliderScalar(),VSliderFloat(),VSliderInt(),VSliderScalar() - Drags:
DragFloat(),DragInt(),DragScalar(),DragFloatRange2(),DragIntRange2() - Input:
InputText(),InputTextMultiline(),InputFloat(),InputInt(),InputDouble(),InputScalar() - Color:
ColorEdit3(),ColorEdit4(),ColorPicker3(),ColorPicker4(),ColorButton() - Trees:
TreeNode(),TreeNodeEx(),TreePush(),TreePop(),CollapsingHeader(),SetNextItemOpen() - Selectables:
Selectable() - Multi-select:
BeginMultiSelect(),EndMultiSelect(),SetNextItemSelectionUserData() - Combo:
BeginCombo(),EndCombo(),Combo() - List box:
BeginListBox(),EndListBox(),ListBox() - Menus:
BeginMenuBar(),EndMenuBar(),BeginMainMenuBar(),EndMainMenuBar(),BeginMenu(),EndMenu(),MenuItem() - Tabs:
BeginTabBar(),EndTabBar(),BeginTabItem(),EndTabItem(),TabItemButton(),SetTabItemClosed() - Tooltips:
SetTooltip(),BeginTooltip(),EndTooltip(),BeginItemTooltip(),SetItemTooltip() - Values:
Value()(convenience wrappers for displaying labeled values) - Images:
Image(),ImageButton() - Progress:
ProgressBar()
imgui_tables.cpp
The complete table system:
BeginTable()/EndTable()— create a table with specified columns and flagsTableSetupColumn()— define column properties (label, flags, initial width)TableHeadersRow()— emit the header row with clickable sort headersTableAngledHeadersRow()— emit angled (rotated) column headersTableNextRow()/TableNextColumn()/TableSetColumnIndex()— navigate cellsTableSetBgColor()— set per-row or per-cell background colorsTableGetSortSpecs()— retrieve current sort specification for implementing custom sort- Column auto-fit, freezing (horizontal/vertical), scrolling, context menu for column visibility
- Per-column state persistence in .ini files
imgui_draw.cpp
Drawing and font systems:
- ImDrawList: all rendering primitives, vertex/index buffer management, draw command batching
- ImFontAtlas: font loading (
AddFontFromFileTTF,AddFontFromMemoryTTF,AddFontDefault), atlas building, glyph lookup, custom rectangles - ImFont: per-font glyph data, text measurement (
CalcTextSizeA), rendering - ImTextureData: texture metadata and pixel data management (v1.92+)
- Polyline rendering: anti-aliased line and fill algorithms
imgui_demo.cpp
The interactive demo window (ShowDemoWindow()) demonstrates every feature with inline source code. It serves as both documentation and testing surface. Widgets are organized by category with collapsing sections. The demo window is the primary learning resource for Dear ImGui.
misc/freetype/imgui_freetype.cpp
Optional FreeType integration for higher-quality font rasterization:
- Better hinting and anti-aliasing than stb_truetype
- SVG-in-OpenType support (emoji fonts, color fonts) via plutosvg or lunasvg
- Dynamic font scaling improvements
- Enable with
IMGUI_ENABLE_FREETYPEinimconfig.h
misc/cpp/imgui_stdlib.cpp
std::string wrapper for InputText:
#include "misc/cpp/imgui_stdlib.h"
std::string my_string = "Hello";
ImGui::InputText("Label", &my_string); // Resizes std::string automatically
misc/debuggers/
Debugger visualization helpers:
| File | Debugger | Purpose |
|---|---|---|
imgui.natvis |
Visual Studio | Type visualization for ImVector, ImVec2, ImVec4, ImRect, ImGuiWindow, etc. |
imgui.natstepfilter |
Visual Studio | Step filter to skip over ImGui wrapper functions during debugging |
imgui.gdb |
GDB | Pretty printers for ImVec2, ImVec4, ImRect |
imgui_lldb.py |
LLDB | Synthetic children for ImVector, ImSpan, ImRect, ImGuiWindow |
8.6 Code Patterns & Conventions
Formatting
- Indentation: 4 spaces (no tabs)
- Braces: Opening brace on the same line for functions and control flow
- Line length: No strict limit, but generally under ~120 characters
Naming
| Category | Convention | Example |
|---|---|---|
| Local variables | snake_case |
float drag_threshold |
| Functions | PascalCase |
void RenderText() |
| Struct members | PascalCase |
ImVec2 DisplaySize |
| Enum values | PascalCase_ |
ImGuiWindowFlags_NoResize |
| Macros | UPPER_SNAKE_CASE |
IMGUI_API, IM_ASSERT |
| Private/internal | Leading underscore or in imgui_internal.h |
_Current (context field) |
Comments
// Text comment describing behavior
//FunctionCall(); // Commented-out code (no space after //)
C++ Usage
Dear ImGui intentionally uses minimal C++ features:
- No exceptions, no RTTI
- No STL containers in the public API (uses
ImVectorinternally) - C-style casts preferred over C++ casts
- Limited template usage
- No virtual functions in the public API
ImVec2andImVec4are plain structs, not classes
Public API Conventions
- All public functions are in the
ImGui::namespace - All public symbols are decorated with
IMGUI_API - Enum types use a trailing underscore:
ImGuiWindowFlags_ - Flag enums use power-of-two values for bitwise combination
- Output parameters are typically the first pointer argument
- Return values indicate interaction (e.g.,
Button()returnstruewhen clicked)
8.7 Testing
Dear ImGui Test Engine
The primary testing tool is the Dear ImGui Test Engine (ocornut/imgui_test_engine), a separate repository. It provides:
- Simulated input (mouse clicks, keyboard input, navigation)
- Automated UI interaction testing
- Screenshot comparison
- Performance benchmarking
- Enabled by defining
IMGUI_ENABLE_TEST_ENGINEinimconfig.h
CI / Build Verification
GitHub Actions workflows verify that Dear ImGui compiles cleanly across:
- Multiple compilers (GCC, Clang, MSVC)
- Multiple platforms (Windows, Linux, macOS)
- Multiple C++ standards (C++11 through C++20)
- All example applications
Static Analysis
- PVS-Studio: Used for static analysis (configuration in repository)
- Code coverage: OpenCppCoverage for measuring test coverage on Windows
Version Checking
// In your main file — detects config/version mismatches across translation units
IMGUI_CHECKVERSION();
IMGUI_CHECKVERSION() compares the version string, sizeof(ImGuiIO), and sizeof(ImGuiStyle) against the compiled library. A mismatch indicates that different translation units are using different imconfig.h settings or different Dear ImGui versions — a guaranteed crash source.
8.8 Contributing
Contributor License Agreement
All code contributed to Dear ImGui becomes part of the project under the MIT license. Copyright is assigned to the project maintainer (Omar Cornut / ocornut).
Branch Strategy
master— Stable releases and ongoing developmentdocking— Multi-viewport and docking branch (experimental features)- Feature branches for pull requests
Code Style Requirements
- Match existing conventions exactly: 4 spaces, naming patterns, comment style
- Include screenshots or GIFs for any visual changes
- Provide a Minimal Complete Verifiable Example (MCVE) for bug reports
Issue Reporting
- Bugs: GitHub Issues with MCVE
- Feature requests: GitHub Issues with use case description
- Build/linking help: GitHub Discussions (not Issues)
- Cheating-related: Not accepted. Explicitly excluded in CONTRIBUTING.md.
9. Integration Points
Language Bindings
Dear ImGui has bindings for virtually every programming language. The two primary C wrapper projects are:
| Project | Approach | Status |
|---|---|---|
| cimgui | Hand-maintained C wrapper | Mature, widely used |
| dear_bindings | Auto-generated from imgui.h | Newer, more complete coverage |
Auto-generated bindings exist for:
| Language | Notable Projects |
|---|---|
| C# | ImGui.NET |
| Python | pyimgui, Dear PyGui |
| Rust | imgui-rs |
| Go | imgui-go |
| Java | imgui-java |
| Lua | Multiple bindings |
| Nim | nimgl/imgui |
| Zig | zig-imgui |
| JavaScript/TypeScript | imgui-js |
| D | d-imgui |
| Odin | odin-imgui |
| Pascal | Multiple bindings |
Framework Integrations
Dear ImGui integrates with major game engines and application frameworks:
| Framework | Integration Approach |
|---|---|
| Unity | UPM package with native plugin |
| Unreal Engine | Plugin with Slate/RHI backend |
| Godot | GDNative/GDExtension plugin |
| Qt | QWidget/QOpenGLWidget integration |
| SDL | Official backends (SDL2, SDL3) |
| SFML | Community backends |
| raylib | Community backends |
| Sokol | Community backend |
Notable Extensions
| Extension | Purpose | Repository |
|---|---|---|
| ImPlot | 2D plotting (line, scatter, bar, heatmap, etc.) | epezent/implot |
| ImPlot3D | 3D plotting | brenocq/implot3d |
| ImGuizmo | 3D gizmos (translate, rotate, scale) | CedricGuillemet/ImGuizmo |
| ImNodes | Node editor | Nelarius/imnodes |
| ImGuiColorTextEdit | Text editor with syntax highlighting | BalazsJako/ImGuiColorTextEdit |
| ImGuiFileDialog | File browser dialog | aiekick/ImGuiFileDialog |
| Dear ImGui Test Engine | Automated testing | ocornut/imgui_test_engine |
| imgui-module | C++20 modules support | stripe2933/imgui-module |
Custom Widget Creation
Create custom widgets using the low-level ImDrawList API combined with cursor and item registration:
void MyCustomWidget(const char* label, float* value) {
ImGuiWindow* window = ImGui::GetCurrentWindow();
if (window->SkipItems) return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
ImVec2 pos = window->DC.CursorPos;
ImVec2 size(200, 30);
ImRect bb(pos, ImVec2(pos.x + size.x, pos.y + size.y));
ImGui::ItemSize(size);
if (!ImGui::ItemAdd(bb, id)) return;
bool hovered, held;
bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held);
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddRectFilled(bb.Min, bb.Max,
ImGui::GetColorU32(held ? ImGuiCol_ButtonActive :
hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button));
// ... draw your widget content ...
}
Custom Backend Creation
To create a custom platform or renderer backend:
Platform Backend Template:
// imgui_impl_myplatform.h
#pragma once
#include "imgui.h"
bool ImGui_ImplMyPlatform_Init(MyWindowHandle* window);
void ImGui_ImplMyPlatform_Shutdown();
void ImGui_ImplMyPlatform_NewFrame();
// imgui_impl_myplatform.cpp
#include "imgui.h"
#include "imgui_impl_myplatform.h"
struct ImGui_ImplMyPlatform_Data {
MyWindowHandle* Window;
double Time;
// ... platform-specific state ...
};
static ImGui_ImplMyPlatform_Data* ImGui_ImplMyPlatform_GetBackendData() {
return ImGui::GetCurrentContext()
? (ImGui_ImplMyPlatform_Data*)ImGui::GetIO().BackendPlatformUserData
: NULL;
}
bool ImGui_ImplMyPlatform_Init(MyWindowHandle* window) {
ImGuiIO& io = ImGui::GetIO();
auto* bd = IM_NEW(ImGui_ImplMyPlatform_Data)();
io.BackendPlatformUserData = (void*)bd;
io.BackendPlatformName = "imgui_impl_myplatform";
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos;
bd->Window = window;
bd->Time = 0.0;
// Set up clipboard functions
io.PlatformIO.Platform_GetClipboardTextFn = MyGetClipboardText;
io.PlatformIO.Platform_SetClipboardTextFn = MySetClipboardText;
return true;
}
void ImGui_ImplMyPlatform_NewFrame() {
ImGuiIO& io = ImGui::GetIO();
auto* bd = ImGui_ImplMyPlatform_GetBackendData();
// Update display size
int w, h;
MyGetWindowSize(bd->Window, &w, &h);
io.DisplaySize = ImVec2((float)w, (float)h);
// Update delta time
double current_time = MyGetTime();
io.DeltaTime = bd->Time > 0.0
? (float)(current_time - bd->Time)
: (float)(1.0f / 60.0f);
bd->Time = current_time;
// Feed mouse input
io.AddMousePosEvent(MyGetMouseX(), MyGetMouseY());
io.AddMouseButtonEvent(0, MyIsMouseDown(MOUSE_LEFT));
io.AddMouseButtonEvent(1, MyIsMouseDown(MOUSE_RIGHT));
io.AddMouseButtonEvent(2, MyIsMouseDown(MOUSE_MIDDLE));
// Feed keyboard input (for each key event since last frame)
// io.AddKeyEvent(ImGuiKey_..., is_pressed);
}
void ImGui_ImplMyPlatform_Shutdown() {
auto* bd = ImGui_ImplMyPlatform_GetBackendData();
ImGuiIO& io = ImGui::GetIO();
io.BackendPlatformUserData = NULL;
io.BackendPlatformName = NULL;
IM_DELETE(bd);
}
Renderer Backend Template (render loop core):
void ImGui_ImplMyRenderer_RenderDrawData(ImDrawData* draw_data) {
// Set up orthographic projection
float L = draw_data->DisplayPos.x;
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
MySetProjectionMatrix(L, R, T, B);
ImVec2 clip_off = draw_data->DisplayPos;
ImVec2 clip_scale = draw_data->FramebufferScale;
for (int n = 0; n < draw_data->CmdListsCount; n++) {
const ImDrawList* cmd_list = draw_data->CmdLists[n];
// Upload vertex/index data
MyUploadVertexBuffer(cmd_list->VtxBuffer.Data,
cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
MyUploadIndexBuffer(cmd_list->IdxBuffer.Data,
cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) {
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback) {
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
MyResetRenderState(draw_data);
else
pcmd->UserCallback(cmd_list, pcmd);
continue;
}
// Compute clip rectangle
ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x,
(pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x,
(pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
continue;
MySetScissorRect((int)clip_min.x, (int)clip_min.y,
(int)(clip_max.x - clip_min.x),
(int)(clip_max.y - clip_min.y));
MyBindTexture(pcmd->GetTexID());
MyDrawIndexed(pcmd->ElemCount,
pcmd->IdxOffset,
pcmd->VtxOffset);
}
}
}
ImDrawVert Layout
The vertex format used by Dear ImGui:
struct ImDrawVert {
ImVec2 pos; // 2 floats: screen-space position
ImVec2 uv; // 2 floats: texture coordinates
ImU32 col; // 4 bytes: packed RGBA color (or BGRA with IMGUI_USE_BGRA_PACKED_COLOR)
};
// Total: 20 bytes per vertex (no padding on most platforms)
Your renderer's vertex input layout must match this structure exactly. The position is in screen-space pixels (not normalized). The UV coordinates reference the font atlas texture. The color is pre-multiplied by alpha in some cases (check your blending setup).
Recommended Blend State
Dear ImGui expects alpha blending to be enabled:
SrcBlend = SRC_ALPHA
DstBlend = ONE_MINUS_SRC_ALPHA
SrcBlendAlpha = ONE
DstBlendAlpha = ONE_MINUS_SRC_ALPHA
BlendOp = ADD
Disable depth testing and backface culling. Enable scissor testing.
10. Troubleshooting
Build & Link Errors
Problem: Undefined reference to ImGui::CreateContext() or other Dear ImGui functions.
Solution: Ensure all required .cpp files are compiled and linked: imgui.cpp, imgui_draw.cpp, imgui_tables.cpp, imgui_widgets.cpp, plus your chosen backend files.
Problem: Multiple definition errors for Dear ImGui symbols.
Solution: Each .cpp file should be compiled exactly once. If using imgui_single_file.h, do not also compile the individual .cpp files. If using a build system, ensure Dear ImGui sources are not added to multiple targets without proper linking.
Problem: IMGUI_CHECKVERSION() assertion fails.
Solution: Different translation units are seeing different imconfig.h settings or different Dear ImGui versions. Ensure all files include the same imconfig.h and the same version of Dear ImGui headers.
Problem: Linker errors related to stb_truetype or stb_rect_pack duplicate symbols.
Solution: If you compile stb libraries separately, define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION and/or IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION in imconfig.h.
Problem: "Cannot open include file: 'imgui.h'" in backend files.
Solution: Add the Dear ImGui root directory to your include path. Backend files include "imgui.h" without a path prefix.
Backend Initialization
Problem: Black screen after initialization — no UI visible.
Solution: Verify that io.DisplaySize is set to valid (non-zero) values. Check that the rendering clear color is different from the window background color. Ensure ImGui::Render() is called after ImGui::EndFrame() (which is called automatically by Render()).
Problem: UI renders but doesn't respond to input.
Solution: Verify that the platform backend is feeding input events (check io.MousePos, io.KeysDown in the Metrics window). Ensure ImGui::NewFrame() is called before any widget code. Check io.WantCaptureMouse / io.WantCaptureKeyboard — if you're filtering events based on these, ensure you're checking them at the right time (after NewFrame()).
Problem: Crash on ImGui::NewFrame() — null pointer dereference.
Solution: The font atlas has not been built. Ensure at least one font is loaded (or use AddFontDefault()) and that the atlas texture has been uploaded to the GPU before the first frame.
Problem: Assertion g.IO.DeltaTime >= 0.0f or extreme layout jitter.
Solution: io.DeltaTime must be positive. A value of 0.0f or negative causes division-by-zero or infinite values in layout. Ensure your frame timing code handles edge cases (first frame, breakpoints, system sleep).
Font & Text Rendering
Problem: Text appears as white rectangles or question marks.
Solution: The font atlas texture was not uploaded to the GPU, or the texture ID is incorrect. Rebuild the atlas and re-upload after adding fonts. Check that io.Fonts->TexID matches the GPU texture handle.
Problem: Chinese/Japanese/Korean characters display as ? or boxes.
Solution: Load a font that contains CJK glyphs and specify the appropriate glyph range:
io.Fonts->AddFontFromFileTTF("NotoSansCJK.ttf", 18.0f, NULL,
io.Fonts->GetGlyphRangesChineseFull());
Problem: Font is blurry or too small/large on high-DPI displays.
Solution: Use style.FontScaleDpi to account for display scaling. Load fonts at a higher pixel size (e.g., 2x the desired display size) and set the scale accordingly. FreeType (IMGUI_ENABLE_FREETYPE) provides better hinting at various sizes.
Problem: Font atlas texture is too large (exceeds GPU texture size limit).
Solution: Reduce the number of fonts or glyph ranges. Use ImFontAtlasFlags_NoPowerOfTwoHeight to avoid wasting space. Consider using multiple atlases or loading only the glyph ranges you need.
Tables
Problem: Table columns have unexpected widths or don't resize properly.
Solution: Check ImGuiTableFlags_SizingFixedFit vs ImGuiTableFlags_SizingStretchProp. Fixed-fit columns need explicit widths in TableSetupColumn(). Stretch columns divide available space proportionally.
Problem: Table sort specification not updating when headers are clicked.
Solution: You must call TableGetSortSpecs() each frame and check specs->SpecsDirty. When dirty, re-sort your data and set specs->SpecsDirty = false.
Problem: Assertion failure or visual corruption with many table columns.
Solution: Tables support up to 64 columns. If you need more, consider a different layout approach. For wide tables, enable ImGuiTableFlags_ScrollX.
Drawing
Problem: IM_ASSERT failure: thickness must be > 0.0f in AddLine or similar.
Solution: Ensure all line thickness values are strictly positive. A thickness of 0.0f is not valid. Use 1.0f as the minimum.
Problem: Draw list vertex overflow — assertion on vertex count.
Solution: Define ImDrawIdx as unsigned int in imconfig.h for 32-bit indices, or ensure your renderer supports ImDrawCmd::VtxOffset (set ImGuiBackendFlags_RendererHasVtxOffset).
Problem: Textures display with wrong filtering (pixelated or blurry).
Solution: Texture sampling depends on your renderer's sampler state. Dear ImGui 1.92+ supports ImDrawCallback_SetSamplerLinear and ImDrawCallback_SetSamplerNearest callbacks for per-draw-command sampler control. Ensure your renderer backend handles these callbacks if you mix pixel art and smooth textures.
Navigation
Problem: Keyboard/gamepad navigation doesn't work. Solution: Enable navigation via config flags:
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
For gamepad, the platform backend must also set ImGuiBackendFlags_HasGamepad and feed gamepad input.
Problem: Navigation skips certain widgets or gets "stuck."
Solution: Some widgets (like InvisibleButton or widgets with ImGuiItemFlags_NoNav) are excluded from navigation. Check if the widget explicitly opts out. For custom widgets, ensure ImGui::ItemAdd() is called with a valid ID.
Settings (.ini)
Problem: Window positions reset every launch.
Solution: Verify io.IniFilename is set to a writable path. Check that the application exits cleanly (calls ImGui::DestroyContext()), which triggers the auto-save. Alternatively, call SaveIniSettingsToDisk() explicitly.
Problem: .ini file grows very large or contains stale entries.
Solution: Windows that are created once and never shown again still persist in the .ini file. Use ImGuiWindowFlags_NoSavedSettings for temporary/transient windows. Manually delete the .ini file to reset.
Problem: .ini file from an older version causes layout issues.
Solution: Dear ImGui handles version changes gracefully — unrecognized sections are ignored. However, if layouts look wrong, delete the .ini file to start fresh. Consider versioning your .ini filename (e.g., myapp_v2.ini) when making significant layout changes.
DPI & Scaling
Problem: UI is too small on 4K/HiDPI displays.
Solution: Use the platform backend's DPI detection and set style.FontScaleDpi accordingly. Load fonts at a higher size (e.g., round(13 * dpi_scale) for the default font). On Windows, the Win32 backend handles DPI awareness via ImGui_ImplWin32_EnableDpiAwareness().
Problem: UI is rendered at the correct size but the framebuffer is wrong (blurry).
Solution: Distinguish between window size (logical pixels) and framebuffer size (physical pixels). Set io.DisplaySize to the window size, and set io.DisplayFramebufferScale to the ratio of framebuffer-to-window size. The Vulkan, Metal, and some OpenGL backends handle this automatically.
Memory
Problem: Memory leak in custom backend.
Solution: Ensure you destroy all GPU resources (textures, buffers, pipelines) in your backend's shutdown function. If using the platform_io.Textures[] system, process pending texture destruction requests each frame. Call ImGui::DestroyContext() on shutdown.
Problem: IM_ASSERT failure in allocator.
Solution: If you use SetAllocatorFunctions(), ensure the functions are set before CreateContext() and remain valid for the lifetime of the context. When using DLLs, set allocators in each DLL.
Miscellaneous
Warning
When
IsItemHovered()orIsItemActive()returns unexpected values, check the order of your calls. These functions always refer to the last item submitted. If you callButton("A")thenText("B"),IsItemHovered()refers to theText, not theButton. Query interaction state immediately after the widget call.
Problem: Two widgets share state (sliders move together, checkboxes toggle together).
Solution: This is an ID conflict. The two widgets have the same ID. Use PushID() / PopID() to add unique identifiers, or use the "##" separator in labels to add hidden ID suffixes:
ImGui::Button("OK##dialog1");
ImGui::Button("OK##dialog2");
Problem: Popup appears and immediately closes.
Solution: OpenPopup() and BeginPopup() must be called in the same ID scope (same window). Ensure OpenPopup() is not called every frame — it should be called only on the triggering event (e.g., inside an if (Button(...)) block).
Problem: Begin()/End() mismatch assertion.
Solution: Every ImGui::Begin() must have a matching ImGui::End(), even when Begin() returns false (window is collapsed/clipped). The false return means you can skip content but must still call End().
Problem: Context menu does not appear on right-click.
Solution: Use BeginPopupContextItem() immediately after the target widget, or BeginPopupContextWindow() for window-level context menus. Ensure ImGuiPopupFlags_MouseButtonRight is used (this is the default for context popup functions). If the popup was previously opened and closed, it may need ImGuiPopupFlags_NoReopen to avoid flickering.
Problem: Drag-and-drop payload is not received by the target.
Solution: Verify that the payload type string matches exactly between SetDragDropPayload() and AcceptDragDropPayload(). Check that BeginDragDropTarget() is called immediately after the receiving widget (it applies to the last item). Ensure the source does not use ImGuiDragDropFlags_PayloadNoCrossContext if source and target are in different contexts.
Problem: InputText does not accept certain characters.
Solution: Check if ImGuiInputTextFlags_CharsDecimal, CharsHexadecimal, CharsUppercase, or CharsNoBlank is set. These flags filter input characters. Use a CallbackCharFilter for custom filtering logic.
Problem: InputText buffer overflow or truncation.
Solution: The buf_size parameter must include space for the null terminator. A buffer of size 64 can hold 63 characters plus \0. For dynamic resizing with std::string, use the misc/cpp/imgui_stdlib.h wrapper with ImGuiInputTextFlags_CallbackResize.
Problem: Colors look wrong (swapped red/blue channels).
Solution: If using IMGUI_USE_BGRA_PACKED_COLOR, ensure your renderer expects BGRA vertex colors. DirectX typically uses BGRA; OpenGL typically uses RGBA. Mismatch between the define and your renderer causes red/blue channel swap.
Problem: Multi-select does not work — only one item can be selected.
Solution: Multi-select requires wrapping your selection loop with BeginMultiSelect() / EndMultiSelect() and processing the ImGuiMultiSelectIO requests returned by these functions. Each selectable item must call SetNextItemSelectionUserData() before the Selectable() call. Without BeginMultiSelect(), each Selectable() operates independently.
Problem: Table columns reappear after being hidden via the context menu.
Solution: Table state is persisted in the .ini file. If you recreate the table with a different column count or different column setup, the old state may conflict. Use ImGuiTableFlags_NoSavedSettings for tables whose column structure changes dynamically, or change the table's string ID when the structure changes.
Problem: ShowDemoWindow() is not available / linker error.
Solution: imgui_demo.cpp must be compiled and linked. If you defined IMGUI_DISABLE_DEMO_WINDOWS, the demo window code is stripped. Remove that define or don't call ShowDemoWindow().
Problem: Assertion window->IDStack.Size > 0 or similar ID stack assertion.
Solution: You have mismatched PushID() / PopID() calls. Every PushID() must have exactly one matching PopID(). Use the ID Stack Tool (ShowIDStackToolWindow()) to inspect the stack at runtime.
Problem: ImGui::Image() displays a white rectangle instead of the texture.
Solution: The texture ID passed to Image() does not match a valid GPU texture handle. Verify that the texture was uploaded to the GPU and that the handle (stored as ImTextureID) is correct. On some backends, the texture handle is a pointer; on others, it is an integer. Ensure the type matches your backend's expectations.
Problem: Keyboard shortcuts fire in the wrong window.
Solution: Dear ImGui routes keyboard shortcuts to the focused window. Use ImGui::SetNextWindowFocus() or ensure the correct window has focus when the shortcut should be active. For global shortcuts, process them in your application code before ImGui::NewFrame(), checking io.WantCaptureKeyboard to avoid conflicts.
Problem: Application freezes or hangs during ImGui::Render().
Solution: This typically indicates an infinite loop in layout calculation, caused by contradictory size constraints (e.g., a child window that auto-resizes based on content that auto-resizes based on the child window). Simplify the layout to break the circular dependency.
Problem: ImGui::GetIO() crashes or returns garbage.
Solution: No context has been created. Call ImGui::CreateContext() before any other Dear ImGui function. If using multiple threads, ensure each thread that calls Dear ImGui has the correct context set via ImGui::SetCurrentContext().
11. Reference
11.1 Version History
Current: v1.92.8 WIP (commit bda4982, 2026-04-24)
| Version | Notable Changes |
|---|---|
| 1.92 | ImTextureRef/ImTextureData system, dynamic font atlas, FontSizeBase/FontScaleMain/FontScaleDpi style fields, tree connecting lines, RendererHasTextures backend flag, sampler callbacks |
| 1.91 | Multi-select API (BeginMultiSelect/EndMultiSelect), box selection, ImGuiMultiSelectFlags_ |
| 1.90 | ImGuiChildFlags_ (new BeginChild() overloads), tab bar overline, image border |
| 1.89 | Tables improvements, ImGuiTableFlags_HighlightHoveredColumn, angled headers |
| 1.88 | IsKeyDown()/IsMouseDown() with ImGuiKey, localization support |
| 1.87 | ImGuiMod_Ctrl/Shift/Alt/Super modifiers, io.AddKeyEvent() queue-based input |
| 1.86 | ImGuiKey enum for all keys (replacing raw indices) |
| 1.85 | SetNextWindowScroll(), InputTextMultiline improvements |
| 1.84 | ImGuiTableFlags_ overhaul, TableGetColumnFlags() |
| 1.80 | Table API initial release (BeginTable/EndTable), replaced legacy Columns API |
Branches:
master— Stable releases and ongoing developmentdocking— Multi-viewport + docking features (experimental, API subject to change)
11.2 Embedded Fonts
| Font | File | Style | License |
|---|---|---|---|
| ProggyClean | misc/fonts/ProggyClean.ttf |
Monospace, 13px bitmap | MIT (Tristan Grimmer) |
| ProggyForever | (embedded in code) | Monospace, scalable | MIT (Disco Hello, Tristan Grimmer) |
| ProggyTiny | misc/fonts/ProggyTiny.ttf |
Monospace, 10px bitmap | MIT (Tristan Grimmer) |
| Cousine-Regular | misc/fonts/Cousine-Regular.ttf |
Monospace | Apache 2.0 (Google) |
| DroidSans | misc/fonts/DroidSans.ttf |
Sans-serif | Apache 2.0 (Google/Ascender) |
| Karla-Regular | misc/fonts/Karla-Regular.ttf |
Sans-serif | SIL Open Font License |
| Roboto-Medium | misc/fonts/Roboto-Medium.ttf |
Sans-serif, medium weight | Apache 2.0 (Google) |
The default font (ProggyClean 13px) is embedded in the source code and available without loading any file. Define IMGUI_DISABLE_DEFAULT_FONT to remove it and save ~10KB of binary size.
11.3 Embedded Third-Party Libraries
| Library | Header | Version | Purpose | License |
|---|---|---|---|---|
| stb_textedit | imstb_textedit.h |
1.14 | Single-line and multi-line text editing (cursor, selection, undo) | Public Domain / MIT |
| stb_truetype | imstb_truetype.h |
1.26 | TrueType font loading and rasterization | Public Domain / MIT |
| stb_rect_pack | imstb_rectpack.h |
1.01 | Rectangle bin-packing for font atlas texture | Public Domain / MIT |
These are vendored copies of Sean Barrett's stb single-header libraries, with minor modifications. Override paths with IMGUI_STB_TRUETYPE_FILENAME, IMGUI_STB_RECT_PACK_FILENAME, or IMGUI_STB_SPRINTF_FILENAME to use your own versions.
11.4 Example Applications
The examples/ directory contains 26 ready-to-build applications demonstrating different platform + renderer combinations:
| Example | Platform | Renderer | Build System | Notes |
|---|---|---|---|---|
example_win32_directx9 |
Win32 | DirectX 9 | VS sln | Legacy, wide compatibility |
example_win32_directx10 |
Win32 | DirectX 10 | VS sln | — |
example_win32_directx11 |
Win32 | DirectX 11 | VS sln | Most common Windows choice |
example_win32_directx12 |
Win32 | DirectX 12 | VS sln | Requires descriptor heap setup |
example_win32_opengl3 |
Win32 | OpenGL 3 | VS sln | Uses built-in GL loader |
example_glfw_opengl2 |
GLFW | OpenGL 2 | Makefile | Legacy fixed-function |
example_glfw_opengl3 |
GLFW | OpenGL 3 | Makefile, VS sln, Emscripten | Cross-platform, recommended starting point |
example_glfw_vulkan |
GLFW | Vulkan | Makefile, VS sln | Requires Vulkan SDK |
example_glfw_metal |
GLFW | Metal | Xcode | macOS only |
example_sdl2_opengl2 |
SDL2 | OpenGL 2 | Makefile, VS sln | Legacy |
example_sdl2_opengl3 |
SDL2 | OpenGL 3 | Makefile, VS sln, Emscripten | Cross-platform |
example_sdl2_vulkan |
SDL2 | Vulkan | Makefile, VS sln | Requires Vulkan SDK |
example_sdl2_sdlrenderer2 |
SDL2 | SDL_Renderer | Makefile, VS sln | Easiest SDL2 setup |
example_sdl3_opengl3 |
SDL3 | OpenGL 3 | Makefile, VS sln | Latest SDL |
example_sdl3_vulkan |
SDL3 | Vulkan | Makefile, VS sln | Requires Vulkan SDK |
example_sdl3_sdlgpu3 |
SDL3 | SDL_GPU | Makefile, VS sln | SDL3's cross-API abstraction |
example_sdl3_sdlrenderer3 |
SDL3 | SDL_Renderer3 | Makefile, VS sln | Easiest SDL3 setup |
example_apple_metal |
AppKit/UIKit | Metal | Xcode | macOS + iOS |
example_apple_opengl2 |
GLUT | OpenGL 2 | Xcode | macOS legacy |
example_android_opengl3 |
Android Native | OpenGL ES 3 | Gradle + CMake | Android Studio project |
example_emscripten_wgpu |
Emscripten | WebGPU | Makefile | Browser-based, recommended for web |
example_allegro5 |
Allegro 5 | Allegro 5 | Makefile, VS sln | Combined backend |
example_glut_opengl2 |
GLUT | OpenGL 2 | Makefile, VS sln | Legacy, not recommended |
example_null |
Null | Null | Makefile, VS sln | Headless, for CI/testing |
11.5 Commonly Used Public API Functions (Quick Reference)
Context & Lifecycle
| Function | Description |
|---|---|
CreateContext() |
Create a new ImGui context |
DestroyContext() |
Destroy the context, free all resources |
GetCurrentContext() |
Get the current context |
SetCurrentContext() |
Set the active context (for multi-context or DLL use) |
NewFrame() |
Start a new frame; must call before any widget |
Render() |
Finalize the frame and prepare draw data |
GetDrawData() |
Get the draw data produced by Render() |
EndFrame() |
End the frame (called automatically by Render()) |
Windows
| Function | Description |
|---|---|
Begin() / End() |
Create a window. End() must always be called. |
BeginChild() / EndChild() |
Create a child region within a window |
SetNextWindowPos() |
Set position for the next Begin() call |
SetNextWindowSize() |
Set size for the next Begin() call |
SetNextWindowCollapsed() |
Set collapsed state for the next Begin() call |
SetNextWindowFocus() |
Focus the next Begin() window |
SetNextWindowBgAlpha() |
Set background alpha for the next Begin() window |
GetWindowPos() / GetWindowSize() |
Get current window geometry |
Layout
| Function | Description |
|---|---|
SameLine() |
Place next widget on the same line |
NewLine() |
Force a new line |
Spacing() |
Add vertical spacing |
Dummy() |
Add an invisible item of specified size |
Indent() / Unindent() |
Adjust horizontal indentation |
BeginGroup() / EndGroup() |
Group items as a single widget for layout |
Separator() |
Draw a horizontal line separator |
GetCursorPos() / SetCursorPos() |
Get/set cursor position within the window |
Style
| Function | Description |
|---|---|
PushStyleColor() / PopStyleColor() |
Override a color temporarily |
PushStyleVar() / PopStyleVar() |
Override a style variable temporarily |
GetStyle() |
Get the current ImGuiStyle struct (mutable) |
StyleColorsDark() |
Apply the dark color theme |
StyleColorsLight() |
Apply the light color theme |
StyleColorsClassic() |
Apply the classic (original) color theme |
Fonts
| Function | Description |
|---|---|
GetIO().Fonts->AddFontDefault() |
Add the embedded ProggyClean font |
GetIO().Fonts->AddFontFromFileTTF() |
Load a font from a TTF file |
GetIO().Fonts->AddFontFromMemoryTTF() |
Load a font from memory |
GetIO().Fonts->Build() |
Build the font atlas |
GetIO().Fonts->GetTexDataAsRGBA32() |
Get atlas pixel data for GPU upload |
PushFont() / PopFont() |
Change the active font temporarily |
Utilities
| Function | Description |
|---|---|
IsItemHovered() |
Was the last item hovered? |
IsItemActive() |
Was the last item active (held)? |
IsItemClicked() |
Was the last item clicked? |
IsItemVisible() |
Is the last item visible (not clipped)? |
GetItemRectMin() / GetItemRectMax() |
Get the bounding rect of the last item |
SetItemDefaultFocus() |
Set keyboard/gamepad focus to the last item |
SetTooltip() |
Show a tooltip with formatted text |
CalcTextSize() |
Calculate the size of text with the current font |
GetTime() |
Get the current time (since context creation) |
GetFrameCount() |
Get the current frame number |
SetAllocatorFunctions() |
Override memory allocation functions |
MemAlloc() / MemFree() |
Allocate/free through Dear ImGui's allocator |
11.6 License
Dear ImGui is licensed under the MIT License.
The MIT License (MIT)
Copyright (c) 2014-2026 Omar Cornut
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.