19_C++精灵库之writetxt.h头文件源代码(2026年1月15日版)

#ifndef WRITETXT_H
#define WRITETXT_H

#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <string>
#include <vector>
#include <memory>
#include <unordered_map>
#include "functools.h"

// 字体样式结构体
struct FontStyleInfo {
    std::string name;   // 字体名称
    int size;           // 字体大小
    std::string type;   // 字体类型(normal, bold, italic)
};

// 文本信息结构体
struct TextData {
    std::string text;
    SDL_Color color;
    float x, y;
    std::string align;
    FontStyleInfo font;
    double angle;  // 旋转角度
    // 新增:缓存纹理和尺寸(仅当文字/字体/颜色不变时有效)
    SDL_Texture* cachedTexture = nullptr;
    int cachedWidth = 0;
    int cachedHeight = 0;
    // 新增:判断是否需要更新缓存
    bool needsUpdate(const TextData& other) const {
        return text != other.text ||  x!=other.x || y!=other.y ||
               color.r != other.color.r || color.g != other.color.g || 
               color.b != other.color.b || color.a != other.color.a || 
               font.name != other.font.name || font.size != other.font.size || 
               font.type != other.font.type;
    }
};

// 文本渲染管理器
class TextRenderer {
private:
    std::vector<TextData> textList;  // 存储所有需要渲染的文本
    // 字体缓存:键为"字体名_大小_类型",值为加载的字体
    std::unordered_map<std::string, TTF_Font*> fontCache;     
    // 添加:生成字体缓存的键
    std::string getFontCacheKey(const FontStyleInfo& font) {
        return font.name + "_" + std::to_string(font.size) + "_" + font.type;
    }

public:
    TextRenderer();
    ~TextRenderer();
    std::vector<TextData> & get_textList();
    // 添加文本到渲染队列
    void addText(const TextData& textData);
    TTF_Font* loadFont(FontStyleInfo& font);  // 保持不变
    // 渲染所有文本
    void renderAll(SDL_Renderer* renderer);
    void removeText(const std::string& text);
    // 清除所有文本
    void clear();
};

#endif // WRITETXT_H

关于李兴球

李兴球的博客是Python创意编程原创博客
此条目发表在C++分类目录。将固定链接加入收藏夹。

发表回复