Add TTF support

This commit is contained in:
2025-12-08 21:16:20 +08:00
parent f8f397af50
commit 7067214c34
5 changed files with 61 additions and 2 deletions

View File

@@ -14,7 +14,10 @@ bool GameApplication::initialize() {
SDL_Log("SDL初始化失败: %s", SDL_GetError());
return false;
}
if (!TTF_Init()) {
SDL_Log("无法初始化 SDL_ttf: %s", SDL_GetError());
return false;
}
m_inputManager = std::make_unique<InputManager>();
m_windowManager = std::make_unique<WindowManager>();

View File

@@ -5,7 +5,7 @@
#include "scenes/base/SceneManager.h"
#include "input/InputManager.h"
#include "utils/Config.h"
#include <SDL3_ttf/SDL_ttf.h>
class GameApplication {
private:

View File

@@ -0,0 +1,35 @@
#include "FontManager.h"
#include <stdexcept>
FontManager::FontManager() {
}
FontManager::~FontManager() {
for (auto& pair : m_fonts) {
TTF_CloseFont(pair.second);
}
m_fonts.clear();
}
TTF_Font* FontManager::loadFont(const std::string& fontID, int ptSize) {
std::string path = "assets/fonts/" + fontID;
std::string key = fontID + std::to_string(ptSize);
auto it = m_fonts.find(key);
// 检查字体是否已经加载
if (it != m_fonts.end()) {
return it->second;
}
TTF_Font* font = TTF_OpenFont(path.c_str(), ptSize);
if (!font) {
throw std::runtime_error("无法加载字体: " + key);
}
m_fonts[key] = font;
return font;
}
TTF_Font* FontManager::getFont(const std::string& key) {
auto it = m_fonts.find(key);
return (it != m_fonts.end()) ? it->second : nullptr;
}

View File

@@ -0,0 +1,20 @@
#pragma once
#include <string>
#include <unordered_map>
#include <SDL3_ttf/SDL_ttf.h>
class FontManager {
public:
FontManager();
~FontManager();
// 加载字体(路径 + 字号)
// ptSize 为字号
TTF_Font* loadFont(const std::string& fontID, int ptSize);
// 获取已加载的字体
TTF_Font* getFont(const std::string& key);
private:
// 用哈希表存储字体
std::unordered_map<std::string, TTF_Font*> m_fonts;
};

View File

@@ -58,5 +58,6 @@ SDL_AppResult SDL_AppIterate(void *appstate) {
// 4. 应用退出回调(清理资源)
void SDL_AppQuit(void *appstate, SDL_AppResult result) {
delete static_cast<GameApplication*>(appstate);
TTF_Quit();
SDL_Quit();
}