本文档提供了将 Dear ImGui 集成到您的应用程序中的分步指南。它涵盖了适用于所有支持的平台和渲染 API 的基本集成模式。有关平台特定的集成细节,请参阅桌面集成或移动和 Web 集成。
Dear ImGui 需要与两个后端系统集成
基本集成流程包括四个主要阶段
来源:examples/example_glfw_opengl3/main.cpp80-208
第一步是创建并初始化 Dear ImGui 上下文,它管理所有 ImGui 状态。
关键步骤
IMGUI_CHECKVERSION() 以验证版本一致性(可选但建议)ImGui::CreateContext() 创建 ImGui 上下文ImGui::GetIO() 获取 IO 结构体引用ImGuiConfigFlags_NavEnableKeyboard 等标志配置 IO 选项ImGui::StyleColorsDark() 或其他选项设置视觉外观来源:examples/example_glfw_opengl3/main.cpp80-89 examples/example_glfw_opengl2/main.cpp49-58
Dear ImGui 需要平台(窗口/输入)和渲染器(图形 API)接口的后端实现。
常见的平台后端包括
imgui_impl_glfw.h/cpp)imgui_impl_sdl2.h/cpp / imgui_impl_sdl3.h/cpp)imgui_impl_win32.h/cpp)常见的渲染器后端包括
imgui_impl_opengl3.h/cpp)imgui_impl_opengl2.h/cpp)GLFW + OpenGL 3 示例
ImGui_ImplGlfw_InitForOpenGL(window, true) 初始化 GLFW 平台后端ImGui_ImplOpenGL3_Init(glsl_version) 初始化 OpenGL 3 渲染器后端来源:examples/example_glfw_opengl3/main.cpp40-96 examples/example_glfw_opengl2/main.cpp38-62
ImGui 集成的核心是每帧主循环,它负责
每帧的关键步骤
glfwPollEvents())NewFrame() 函数NewFrame() 函数ImGui::NewFrame()ImGui::Render() 以完成帧渲染ImGui::GetDrawData() 调用渲染器后端的 RenderDrawData() 函数glfwSwapBuffers())来源:examples/example_glfw_opengl3/main.cpp120-194 examples/example_glfw_opengl2/main.cpp85-160
适当的清理可确保在应用程序退出时释放资源
关闭顺序
ImGui_ImplRenderer_Shutdown() 清理渲染器后端资源ImGui_ImplPlatform_Shutdown() 清理平台后端资源ImGui::DestroyContext() 销毁 ImGui 上下文来源:examples/example_glfw_opengl3/main.cpp199-207 examples/example_glfw_opengl2/main.cpp162-170
集成设置完成后,您可以在 ImGui::NewFrame() 和 ImGui::Render() 之间定义窗口和小部件来创建您的 UI。
UI 工作流程示例
ImGui::Begin("Window Title") 启动一个窗口ImGui::Text()ImGui::Button()ImGui::Checkbox()ImGui::SliderFloat(), ImGui::ColorEdit3()ImGui::End() 关闭窗口定义来源:examples/example_glfw_opengl3/main.cpp147-182 examples/example_glfw_opengl2/main.cpp105-140
Dear ImGui 可以处理其 UI 的输入事件,同时允许您的应用程序处理其他用途的输入
io.WantCaptureMouseio.WantCaptureKeyboard来源:examples/example_glfw_opengl3/main.cpp130-135 examples/example_glfw_opengl2/main.cpp88-93
一个完整的基本集成通常遵循以下结构
上图展示了 Dear ImGui 从初始化到关闭的完整集成流程。
来源:examples/example_glfw_opengl3/main.cpp38-208 examples/example_glfw_opengl2/main.cpp36-171
集成 Dear ImGui 时,请记住以下几点
ImGuiConfigFlags_NavEnableKeyboardImGuiConfigFlags_ViewportsEnable 以支持多窗口(需要额外设置)ImGuiConfigFlags_NavEnableKeyboard 以实现完整的键盘控制ImGuiConfigFlags_NavEnableGamepad 以支持游戏手柄来源:examples/example_glfw_opengl3/main.cpp83-85 examples/example_glfw_opengl3/main.cpp98-113