需將 freetype221MT.lib 加入鏈接器輸入依賴。
#include <irrlicht.h>
#include "TTFontManager.h" // 封裝 FreeType 的字體管理器
#include "CGUITTFont.h" // Irrlicht GUI 字體介面實現
using namespace irr;
using namespace irr::core;
using namespace irr::video;
using namespace irr::scene;
using namespace irr::gui;
#pragma comment(lib, "irrlicht.lib")
#pragma comment(lib, "freetype221MT.lib")
int main() {
// 1. 創建設備 (Direct3D 9, 640x480, 16位色)
IrrlichtDevice *device = createDevice(EDT_DIRECT3D9,
dimension2d<s32>(640, 480), 16, false, false, false, 0);
if (!device) return 1;
device->setWindowCaption(L"你好 世界!"); // 窗口標題支援 Unicode
// 2. 獲取核心子系統
IVideoDriver *driver = device->getVideoDriver();
ISceneManager *smgr = device->getSceneManager();
IGUIEnvironment *guienv = device->getGUIEnvironment();
// 3. 內建字體測試 (僅支援 ASCII)
guienv->addStaticText(L"Hello World.", rect<s32>(10,10,200,20), true);
// 4. 初始化 TrueType 字體管理器 (單例模式)
new TTFontManager(driver);
TTFontManager *ttmgr = TTFontManager::GetSingletonPtr();
// 5. 載入系統字體 (宋體 simsun.ttc, 24 像素)
IGUIFont *font = ttmgr->getFont("simsun.ttc", 24);
if (!font) {
device->drop();
return 1;
}
// 6. 建立簡單場景:貼圖立方體 + 相機
ISceneNode *cubeNode = smgr->addCubeSceneNode(100.0f);
ITexture *tex = driver->getTexture("texture.jpg");
cubeNode->setMaterialTexture(0, tex);
cubeNode->setMaterialFlag(EMF_LIGHTING, false); // 無光照,純貼圖
smgr->addCameraSceneNode(0, vector3df(100,100,-100), vector3df(0,0,0));
// 7. 主渲染循環
while (device->run()) {
driver->beginScene(true, true, SColor(255,200,200,255)); // 清屏+深度
smgr->drawAll(); // 繪製 3D 場景
guienv->drawAll(); // 繪製 GUI 元素 (內建字體)
// 使用 FreeType 字體繪製中文 (座標矩形, 顏色紅色)
font->draw(L"這是一段中文,字體為宋體!",
rect<s32>(0,200,200,30),
SColor(255,255,0,0));
driver->endScene();
}
// 8. 資源釋放 (逆序)
font->drop();
delete ttmgr;
device->drop();
return 0;
}
Irrlicht 內建字體 (IGUIFont) 僅支援位圖字體,無法直接渲染 TTF/TTC。TTFontManager 封裝 FreeType 完成:
FT_New_Face)FT_Load_Glyph, FT_Render_Glyph)IGUIFont::draw() 繪製介面(完整封裝代碼較長,見附件 TTFontManager.h/.cpp, CGUITTFont.h/.cpp)
L"" 前綴 → wchar_t* 寬字符串wchar_t / irr::core::stringw)simsun.ttc 為 Windows 系統字體,通常位於 C:\Windows\Fonts\。實際部署時建議:
"./fonts/simsun.ttc"程序啟動後顯示:
| 問題 | 原因 | 解決 |
|---|---|---|
| 中文顯示方框/亂碼 | 字體文件未找到或不含中文字形 | 確認 simsun.ttc 路徑正確;嘗試 msyh.ttc (微軟雅黑) |
| 鏈接錯誤: freetype221MT.lib | 庫文件未加入項目 / 架構不匹配 (x86 vs x64) | 屬性→鏈接器→輸入→附加依賴項;確認 32/64 位一致 |
| 運行崩潰 at FT_Init_FreeType | FreeType 版本與編譯期不一致 | 確保運行時加載的 DLL 與編譯時 .lib 同版本 |
| 字體渲染極慢 | 每幀實時光柵化 | TTFontManager 內部應有字形緩存/圖集機制;檢查實現 |
CGUITTFont 已較完善