1.首先需要使用imgui的依賴
image.png
2.頭文件引用
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_opengl3.h"
3.此時運行代碼會報錯
因為還需要 GLFW 的庫
官方下載地址:
Download | GLFW
這里以我的系統(tǒng) 為例 :windows 64位
image.png
下載完成之后解壓的目錄
image.png
4.引入GLFW庫
找到剛剛下載的庫解壓:
1.添加附加包含目錄
GLFW路徑\include
image.png2.添加lib熊昌,使用和自己編譯同樣版本的lib,我是vc2022
image.png3.鏈接到這個庫
#pragma comment (lib, "glfw3.lib")
image.png
5.使用stb 這個庫加載圖片
1.庫地址:
GitHub | stb庫
2.我們只需要stb_image.h
3.將stb_image.h
添加到我們的項目中
image.png
4.加上頭文件#define STB_IMAGE_IMPLEMENTATION //必須加上 #include "stb_image.h"
image.png
以上準(zhǔn)備階段就ok安吁,開始代碼階段
1.ImGui 是通過紋理來加載圖片的所以我們實現(xiàn)一個從圖片文件加載到紋理
// 從文件加載紋理
bool LoadTextureFromFile(const char* filename, ID3D11ShaderResourceView** out_srv)
{
int width, height, channels;
unsigned char* pixels = stbi_load(filename, &width, &height, &channels, STBI_rgb_alpha);
if (!pixels)
return false;
D3D11_TEXTURE2D_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
D3D11_SUBRESOURCE_DATA subResource;
ZeroMemory(&subResource, sizeof(subResource));
subResource.pSysMem = pixels;
subResource.SysMemPitch = width * 4;
ID3D11Texture2D* pTexture = nullptr;
if (g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture) != S_OK)
{
stbi_image_free(pixels);
return false;
}
// Create texture view
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
ZeroMemory(&srvDesc, sizeof(srvDesc));
srvDesc.Format = desc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
srvDesc.Texture2D.MostDetailedMip = 0;
if (g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, out_srv) != S_OK)
{
pTexture->Release();
stbi_image_free(pixels);
return false;
}
pTexture->Release();
stbi_image_free(pixels);
return true;
}
2.在ImGui 初始化完成之后
// 加載圖片 ID3D11ShaderResourceView* textureSRV = nullptr; if (!LoadTextureFromFile("E:\\summer\\圖片\\gh_89b7666ea8b7_258.jpg", &textureSRV)) { // 加載失敗 return 1; }
image.png
3.ImGui渲染函數(shù)中
{ ImGui::Begin(u8"夏休助手"); ImGui::Text(u8"程序平均幀率 %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::Text(u8"文本測試"); // 圖片顯示 ImGui::Image(textureSRV, ImVec2(200, 200)); ImGui::End(); }
4.運行效果
image.png