概述
imgui在macos操作系统下,加载图片有一点麻烦,尤其是使用自带的渲染方式。
背景知识
首先下载imgui库 github.com/ocornut/img…
代码示例
示例1:加载图片到纹理
id<MTLTexture> Imguihelper::LoadTextureFromResource(std::string imagePath, id<MTLDevice> device)
{
NSURL* url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:imagePath.c_str()]];
NSError* error = nil;
MTKTextureLoader* loader = [[MTKTextureLoader alloc] initWithDevice:device];
// 指定纹理格式和颜色空间选项
NSDictionary *options = @{
MTKTextureLoaderOptionTextureUsage: @(MTLTextureUsageShaderRead),
MTKTextureLoaderOptionSRGB: @(NO), // 使用 sRGB 颜色空间
MTKTextureLoaderOptionTextureStorageMode: @(MTLStorageModeManaged)
};
id<MTLTexture> texture = [loader newTextureWithContentsOfURL:url options:options error:&error];
if(!texture) {
std::cerr << "Failed to load texture: " << error.localizedDescription.UTF8String << std::endl;
}
return texture;
}
示例2:imgui显示图片
void Imguihelper::Image(int x, int y, int width, int height, id<MTLTexture> texture)
{
ImVec2 old = ImGui::GetCursorScreenPos();
ImVec2 p1(x, y);
ImGui::SetCursorScreenPos(p1);
ImGui::Image((ImTextureID)(intptr_t)texture, ImVec2(width, height));
ImGui::SetCursorScreenPos(old);
}
注意
- 加载图片的时候,需要设置正确的参数,否则图片会比较暗
MTKTextureLoaderOptionSRGB: @(NO), // 使用 sRGB 颜色空间