Extra2D/include/resource/text.h

172 lines
3.6 KiB
C++
Raw 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.

#pragma once
#include <resource/resource.h>
#include <resource/font.h>
#include <types/math/color.h>
#include <types/math/vec2.h>
#include <vector>
#include <string>
namespace extra2d {
/**
* @brief 文本对齐方式
*/
enum class TextAlign : uint8 {
Left, // 左对齐
Center, // 居中对齐
Right // 右对齐
};
/**
* @brief 文本顶点结构
*/
struct TextVertex {
Vec2 position; // 位置
Vec2 uv; // UV 坐标
Color color; // 颜色
};
/**
* @brief 文本行信息
*/
struct TextLine {
std::vector<TextVertex> vertices; // 顶点数组
std::vector<uint16> indices; // 索引数组
float width = 0.0f; // 行宽度
float yOffset = 0.0f; // Y 偏移
};
/**
* @brief 文本资源类
*
* 管理文本渲染数据
*/
class Text : public Resource {
public:
Text();
~Text() override;
/**
* @brief 获取资源类型
*/
ResourceType getType() const override { return ResourceType::Text; }
/**
* @brief 设置字体
* @param font 字体指针
*/
void setFont(Ptr<Font> font);
/**
* @brief 获取字体
*/
Font* getFont() const { return font_.get(); }
/**
* @brief 设置文本内容
* @param text 文本字符串
*/
void setText(const std::string& text);
/**
* @brief 获取文本内容
*/
const std::string& getText() const { return text_; }
/**
* @brief 设置字体大小
* @param size 字体大小
*/
void setFontSize(float size);
/**
* @brief 获取字体大小
*/
float getFontSize() const { return fontSize_; }
/**
* @brief 设置颜色
* @param color 颜色
*/
void setColor(const Color& color);
/**
* @brief 获取颜色
*/
const Color& getColor() const { return color_; }
/**
* @brief 设置对齐方式
* @param align 对齐方式
*/
void setAlign(TextAlign align);
/**
* @brief 获取对齐方式
*/
TextAlign getAlign() const { return align_; }
/**
* @brief 设置最大宽度(自动换行)
* @param width 最大宽度0 表示不限制
*/
void setMaxWidth(float width);
/**
* @brief 获取最大宽度
*/
float getMaxWidth() const { return maxWidth_; }
/**
* @brief 设置行间距
* @param spacing 行间距倍数
*/
void setLineSpacing(float spacing);
/**
* @brief 获取行间距
*/
float getLineSpacing() const { return lineSpacing_; }
/**
* @brief 获取文本尺寸
*/
Vec2 getSize() const { return size_; }
/**
* @brief 获取文本行数组
*/
const std::vector<TextLine>& getLines() const { return lines_; }
/**
* @brief 重新生成顶点数据
*/
void rebuild();
/**
* @brief 检查是否需要重建
*/
bool isDirty() const { return dirty_; }
private:
Ptr<Font> font_; // 字体
std::string text_; // 文本内容
float fontSize_ = 16.0f; // 字体大小
Color color_ = Color::White; // 颜色
TextAlign align_ = TextAlign::Left; // 对齐方式
float maxWidth_ = 0.0f; // 最大宽度
float lineSpacing_ = 1.2f; // 行间距
Vec2 size_; // 文本尺寸
std::vector<TextLine> lines_; // 文本行数组
bool dirty_ = true; // 是否需要重建
/**
* @brief 构建顶点数据
*/
void buildVertices();
};
} // namespace extra2d