feat(ui): add auto-scaling option for button and slider text

This commit is contained in:
2026-07-15 15:33:06 +08:00
parent 632ead2e16
commit 7c991f9f5e
4 changed files with 25 additions and 2 deletions

View File

@@ -30,6 +30,8 @@ public:
Button& set_default_image(TextureManager& texture_manager);
Button& set_text(const std::string& text);
Button& set_auto_scale(bool auto_scale);
float scale() const;
template <typename F> Button& set_clicked(F&& f) {
m_clicked = std::forward<F>(f);
@@ -39,6 +41,8 @@ public:
private:
static constexpr float PADDING = 5.0f;
static constexpr float DEFAULT_SCALE = 3.0f;
static constexpr float TEXT_SCALE = 0.6f;
static constexpr const char* DEFAULT_BUTTON_IMAGE =
"texture/ui/button001.png";
std::function<void()> m_clicked;
@@ -48,6 +52,7 @@ private:
float m_width = NORMAL_BUTTON_WIDTH;
float m_height = NORMAL_BUTTON_HEIGHT;
float m_scale = DEFAULT_SCALE;
bool m_auto_scale = false;
void on_render(Renderer& renderer) override;
void on_update(float dt) override;
void update_text_scale();

View File

@@ -30,12 +30,13 @@ public:
TextureManager& texture_manager);
Slider& set_default_image(TextureManager& texture_manager);
Slider& set_auto_scale(bool auto_scale);
bool handle_mouse_move_event(const MouseMoveEvent& e) override;
bool handle_mouse_button_event(const MouseButtonEvent& e) override;
private:
static constexpr float PADDING = 5.0f;
static constexpr float TEXT_SCALE = 0.6f;
static constexpr float DEFAULT_SCALE = 3.0f;
static constexpr const char* DEFAULT_TRACK_IMAGE =
"texture/ui/slider_track001.png";
@@ -51,6 +52,7 @@ private:
float m_xpos = 0.0f;
bool m_dragging = false;
bool m_inside = false;
bool m_auto_scale = false;
float* m_float_value = nullptr;
int* m_int_value = nullptr;
float m_min = 0;

View File

@@ -87,7 +87,16 @@ Button& Button::set_text(const std::string& text) {
return *this;
}
Button& Button::set_auto_scale(bool auto_scale) {
m_auto_scale = auto_scale;
return *this;
}
void Button::update_text_scale() {
if (!m_auto_scale) {
m_foreground->set_scale(TEXT_SCALE);
return;
}
float text_w = m_foreground->real_width();
float text_h = m_foreground->real_height();

View File

@@ -103,7 +103,10 @@ Slider& Slider::set_default_image(TextureManager& texture_manager) {
set_thumb_image(DEFAULT_THUMB_IMAGE, texture_manager);
return set_track_image(DEFAULT_TRACK_IMAGE, texture_manager);
}
Slider& Slider::set_auto_scale(bool auto_scale) {
m_auto_scale = auto_scale;
return *this;
}
bool Slider::handle_mouse_move_event(const MouseMoveEvent& e) {
auto p = pos();
m_xpos = e.xpos;
@@ -212,6 +215,10 @@ void Slider::on_render(Renderer& renderer) {
}
void Slider::update_text_scale() {
if (!m_auto_scale) {
m_label->set_scale(TEXT_SCALE);
return;
}
float text_w = m_label->real_width();
float text_h = m_label->real_height();