mirror of
https://github.com/zhenyan121/SporeBG-Conid.git
synced 2026-04-10 14:24:10 +08:00
Added button handle event
This commit is contained in:
@@ -1,15 +1,25 @@
|
||||
#include "Button.h"
|
||||
#include "graphics/font/TextRenderer.h"
|
||||
|
||||
Button::Button()
|
||||
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
Button::Button(TextRenderer* textRenderer) : m_textRenderer(textRenderer) {
|
||||
}
|
||||
|
||||
void Button::setText(const std::string& text, TextStyle style) {
|
||||
m_buttonData.text = text;
|
||||
m_buttonData.textstytle = style;
|
||||
|
||||
// 如果提供了 TextRenderer,则立即测量文本并更新控件尺寸
|
||||
if (m_textRenderer) {
|
||||
auto [w, h] = m_textRenderer->getTextSize(text, style);
|
||||
m_rect.w = static_cast<float>(w);
|
||||
m_rect.h = static_cast<float>(h);
|
||||
m_buttonData.rect = m_rect;
|
||||
}
|
||||
}
|
||||
|
||||
void Button::setBackgroundColor(SDL_Color normal) {
|
||||
@@ -22,9 +32,23 @@ void Button::setBorder(int thickness, SDL_Color color) {
|
||||
}
|
||||
|
||||
|
||||
void Button::setCallback(std::function<void()> callback) {
|
||||
m_callback = callback;
|
||||
}
|
||||
|
||||
void Button::update(float deltaTime) {
|
||||
|
||||
}
|
||||
void Button::handleCilck(int x, int y) {
|
||||
|
||||
if (m_callback && m_isEnabled && m_isVisible) {
|
||||
//SDL_Log("rect x: %f, y: %f, w: %f, h: %f", m_rect.x, m_rect.y, m_rect.w, m_rect.h);
|
||||
if (x >= m_rect.x && x <= m_rect.x + m_rect.w &&
|
||||
y >= m_rect.y && y <= m_rect.y + m_rect.h) {
|
||||
m_callback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
#pragma once
|
||||
#include "ui/base/UIRenderData.h"
|
||||
#include "ui/base/UIComponent.h"
|
||||
#include <memory>
|
||||
|
||||
// 前向声明,避免在头文件包含过多实现细节
|
||||
class TextRenderer;
|
||||
#include <functional>
|
||||
class Button : public UIComponent{
|
||||
public:
|
||||
// 默认构造(不进行自动测量)
|
||||
Button();
|
||||
// 可以传入 TextRenderer 指针以便在 setText 时立即计算文字尺寸并更新 rect
|
||||
explicit Button(TextRenderer* textRenderer);
|
||||
~Button() override = default;
|
||||
|
||||
// 实现UIComponent接口
|
||||
@@ -31,18 +39,28 @@ public:
|
||||
*/
|
||||
void setBorder(int thickness, SDL_Color color);
|
||||
|
||||
void setCallback(std::function<void()> callback);
|
||||
|
||||
ButtonData& getButtonDate() {
|
||||
m_buttonData.rect = m_rect;
|
||||
return m_buttonData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief 处理点击事件
|
||||
* @param x 点击位置的X坐标
|
||||
* @param y 点击位置的Y坐标
|
||||
*/
|
||||
void handleCilck(int x, int y);
|
||||
|
||||
private:
|
||||
|
||||
|
||||
|
||||
|
||||
std::function<void()> m_callback;
|
||||
ButtonData m_buttonData;
|
||||
// 用于在 setText 时测量文本尺寸(非拥有)
|
||||
TextRenderer* m_textRenderer = nullptr;
|
||||
|
||||
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user