#include "EngineFrame/Component/Text.h" #include "Text.h" #include "EngineCore/Game.h" Text::Text() { } Text::~Text() { } void Text::Init(std::string Str, TTF_Font *font, SDL_Color color) { if (!m_texture) { this->m_font = font; this->m_color = color; } // 先渲染为表面 SDL_Surface *textSurface = TTF_RenderUTF8_Blended(font, Str.c_str(), color); if (!textSurface) { SDL_LogError(0, "文字渲染为表面失败!TTF_Error:%s", TTF_GetError()); } // 转换为RGBA8888格式(与OpenGL的GL_RGBA匹配) SDL_Surface *rgbaSurface = SDL_ConvertSurfaceFormat( textSurface, SDL_PIXELFORMAT_ABGR8888, 0); SDL_FreeSurface(textSurface); // 再将表面转换为纹理 RenderManager *renderer = Game::GetInstance().GetRenderer(); m_texture = new Texture; m_texture->Init(rgbaSurface); // 释放表面 SDL_FreeSurface(rgbaSurface); Sprite::Init(); } void Text::Render() { Sprite::Render(); } void Text::SetText(std::string Str) { if (Str == m_text) return; // 如果有原纹理先删除原纹理 if (m_texture) { m_texture = nullptr; // 置空指针 } m_text = Str; Init(Str, m_font, m_color); } std::string Text::GetText() { return m_text; }