Cocos2d-x的控件類型僅限於基礎的幾種,如label、button、listview等,做游戲開發時基本夠用了。但如果想用cocos2dx來做工具的話,那就有點困難了。
這里介紹一個適合做工具的UI庫:ImGui, 地址:https://github.com/ocornut/imgui。核心文件僅有UI邏輯部分,可接入OpenGL/DX/Cocos2d-x等多種渲染庫。
核心只有4個文件,也是夠小的了。
GitHub上有一個Cocos2d-x lua版+ImGui的庫:https://github.com/c0i/imguix。由於此庫年久失修,在這兒上傳一個ImGui1.6+Cocos2d-x3.16的可用工程。地址:https://pan.baidu.com/s/1IRNYw1PUPvoTIE1kV06Xkw, 效果如下圖:
中文支持: 為ImGui指定一個中文字庫
ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("res/FZCuYuan-M03S.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesChinese());
渲染方式: 在cocos2dx中創建一個特殊的Layer,所有ImGui的內容顯示在此Layer之上。由於Scene會在lua層指定,所以此處用了一個定時器來創建Layer
Director::getInstance()->getScheduler()->schedule([](float) { auto runningScene = Director::getInstance()->getRunningScene(); if (runningScene && !runningScene->getChildByName("ImGUILayer")) { runningScene->addChild(ImGuiLayer::create(), INT_MAX, "ImGUILayer"); } }, this, 0, false, "checkImGUI");
ImGui lua版用法簡介:
在lua層創建一個imgui.draw函數,cocos2dx每幀渲染時都會來執行此函數,所有的imgui操作都需要在此函數內執行。所以如果在此函數內打印日志的話,將會慘不忍睹...
lua層目前導出了button、text、 popupModal、treeNodeEx等各種控件,更多可參見imgui_lua.cpp,imgui示例可參見imgui_demo.cpp。
部分控件方法需要成對出現,如imgui.begin/imgui.endToLua、imgui.treeNodeEx/imgui.treePop、imgui.beginChild/imgui.endChild等,否則將會報"Assertion failed: (g.CurrentWindowStack.Size == 1), function EndFrame"錯誤
在ImGui中,監聽點擊事件非常簡單,判斷函數的返回值即可:
if imgui.button("按鈕") then print("點擊按鈕") end
在ImGui中,控件創建時不需要指定位置,系統會自動排列位置並對齊。當然也可以調用imgui.setCursorPos或imgui.setNextWindowPos來指定位置。
