Files
DNF_DEV/source/EngineFrame/Component/NumberText.cpp

104 lines
2.9 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "NumberText.h"
void NumberText::PreloadDigits()
{
// 需要支持的字符0-9和负号
const std::string digits = "0123456789-";
for (char c : digits)
{
std::string charStr(1, c);
// 渲染单个字符为纹理
SDL_Surface *surface = TTF_RenderUTF8_Blended(m_font, charStr.c_str(), m_color);
if (!surface)
{
SDL_LogError(0, "数字字符渲染数字字符失败:%s", TTF_GetError());
continue;
}
// 转换为RGBA格式
SDL_Surface *rgbaSurface = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_ABGR8888, 0);
SDL_FreeSurface(surface);
// 创建纹理并缓存
Texture *tex = new Texture();
tex->Init(rgbaSurface);
SDL_FreeSurface(rgbaSurface);
m_digitTextures[c] = tex;
}
}
void NumberText::UpdateDigitSprites(const std::string &numStr)
{
// // 先释放旧的精灵
// for (auto *sprite : m_digitSprites)
// {
// if (sprite)
// {
// delete sprite;
// }
// }
// m_digitSprites.clear();
// // 计算总宽度(用于居中或左对齐)
// int totalWidth = 0;
// std::vector<int> charWidths; // 记录每个字符的宽度
// for (char c : numStr)
// {
// auto it = m_digitTextures.find(c);
// if (it == m_digitTextures.end())
// continue; // 跳过不支持的字符
// int w = it->second->getSize().width;
// totalWidth += w;
// charWidths.push_back(w);
// }
// // 绘制每个字符(从左到右排列)
// float currentX = GetWorldPos().x; // 基于当前位置排列
// float currentY = GetWorldPos().y;
// int index = 0;
// for (char c : numStr)
// {
// auto it = m_digitTextures.find(c);
// if (it == m_digitTextures.end())
// continue;
// // 创建字符精灵
// Sprite *sprite = new Sprite();
// sprite->SetTexture(it->second);
// sprite->SetPosition(Vec2(currentX, currentY));
// sprite->SetSize(it->second->getSize());
// m_digitSprites.push_back(sprite);
// // 移动到下一个字符的位置预留1px间距
// currentX += charWidths[index] + 1;
// index++;
// }
}
NumberText::NumberText(TTF_Font *font, SDL_Color color) : m_font(font), m_color(color)
{
PreloadDigits();
}
NumberText::~NumberText()
{
}
void NumberText::SetNumber(int number)
{
if (number == m_currentNumber)
return; // 数字未变化则跳过
m_currentNumber = number;
// 转换数字为字符串(处理负数)
std::string numStr = std::to_string(number);
UpdateDigitSprites(numStr); // 更新数字精灵布局
}
void NumberText::Render()
{
// for (auto *sprite : m_digitSprites)
// {
// if (sprite)
// sprite->Render();
// }
}