refactor: 统一边界框方法名称为 boundingBox

将 getBoundingBox 方法重命名为 boundingBox,以遵循更简洁的命名规范
同时更新相关文档和示例代码中的调用
This commit is contained in:
ChestnutYueyue 2026-02-26 00:55:13 +08:00
parent 377ec373b0
commit ea5ecd383f
39 changed files with 2031 additions and 2149 deletions

View File

@ -316,8 +316,8 @@ if (buttonFrame) {
**按钮使用世界坐标空间World Space** **按钮使用世界坐标空间World Space**
```cpp ```cpp
// Button::getBoundingBox() 返回世界坐标系的包围盒 // Button::boundingBox() 返回世界坐标系的包围盒
Rect Button::getBoundingBox() const { Rect Button::boundingBox() const {
auto pos = getRenderPosition(); // 获取世界坐标位置 auto pos = getRenderPosition(); // 获取世界坐标位置
// ... 计算包围盒 // ... 计算包围盒
return Rect(x0, y0, w, h); // 世界坐标 return Rect(x0, y0, w, h); // 世界坐标

View File

@ -22,7 +22,7 @@ public:
} }
// 必须实现 getBoundingBox 方法 // 必须实现 getBoundingBox 方法
Rect getBoundingBox() const override { Rect boundingBox() const override {
Vec2 pos = getPosition(); Vec2 pos = getPosition();
return Rect(pos.x - width_ / 2, pos.y - height_ / 2, width_, height_); return Rect(pos.x - width_ / 2, pos.y - height_ / 2, width_, height_);
} }
@ -212,7 +212,7 @@ private:
## 关键要点 ## 关键要点
1. **必须调用 `setSpatialIndexed(true)`** - 启用节点的空间索引 1. **必须调用 `setSpatialIndexed(true)`** - 启用节点的空间索引
2. **必须实现 `getBoundingBox()`** - 返回准确的边界框 2. **必须实现 `boundingBox()`** - 返回准确的边界框
3. **在 `onEnter()` 中调用 `Scene::onEnter()`** - 确保节点正确注册到空间索引 3. **在 `onEnter()` 中调用 `Scene::onEnter()`** - 确保节点正确注册到空间索引
4. **使用 `queryCollisions()`** - 自动利用空间索引优化检测 4. **使用 `queryCollisions()`** - 自动利用空间索引优化检测

View File

@ -16,10 +16,11 @@ public:
void setColliding(bool colliding) { isColliding_ = colliding; } void setColliding(bool colliding) { isColliding_ = colliding; }
Rect getBoundingBox() const override { Rect boundingBox() const override {
// 返回实际的矩形边界 // 返回实际的矩形边界
Vec2 position = pos(); Vec2 position = pos();
return Rect(position.x - width_ / 2, position.y - height_ / 2, width_, height_); return Rect(position.x - width_ / 2, position.y - height_ / 2, width_,
height_);
} }
void onRender(RenderBackend &renderer) override { void onRender(RenderBackend &renderer) override {
@ -27,16 +28,16 @@ public:
// 绘制填充矩形 // 绘制填充矩形
Color fillColor = isColliding_ ? Color(1.0f, 0.2f, 0.2f, 0.8f) : color_; Color fillColor = isColliding_ ? Color(1.0f, 0.2f, 0.2f, 0.8f) : color_;
renderer.fillRect( renderer.fillRect(Rect(position.x - width_ / 2, position.y - height_ / 2,
Rect(position.x - width_ / 2, position.y - height_ / 2, width_, height_), width_, height_),
fillColor); fillColor);
// 绘制边框 // 绘制边框
Color borderColor = isColliding_ ? Color(1.0f, 0.0f, 0.0f, 1.0f) Color borderColor = isColliding_ ? Color(1.0f, 0.0f, 0.0f, 1.0f)
: Color(1.0f, 1.0f, 1.0f, 0.5f); : Color(1.0f, 1.0f, 1.0f, 0.5f);
float borderWidth = isColliding_ ? 3.0f : 2.0f; float borderWidth = isColliding_ ? 3.0f : 2.0f;
renderer.drawRect( renderer.drawRect(Rect(position.x - width_ / 2, position.y - height_ / 2,
Rect(position.x - width_ / 2, position.y - height_ / 2, width_, height_), width_, height_),
borderColor, borderWidth); borderColor, borderWidth);
} }
@ -149,7 +150,8 @@ private:
addChild(fpsText_); addChild(fpsText_);
// 创建退出提示文本 // 创建退出提示文本
float screenHeight = static_cast<float>(Application::instance().getConfig().height); float screenHeight =
static_cast<float>(Application::instance().getConfig().height);
exitHintText_ = Text::create("按 + 键退出", infoFont_); exitHintText_ = Text::create("按 + 键退出", infoFont_);
exitHintText_->setPosition(50.0f, screenHeight - 50.0f); exitHintText_->setPosition(50.0f, screenHeight - 50.0f);
exitHintText_->setTextColor(Color(0.8f, 0.8f, 0.8f, 1.0f)); exitHintText_->setTextColor(Color(0.8f, 0.8f, 0.8f, 1.0f));
@ -238,8 +240,7 @@ private:
// 程序入口 // 程序入口
// ============================================================================ // ============================================================================
int main(int argc, char **argv) int main(int argc, char **argv) {
{
// 初始化日志系统 // 初始化日志系统
Logger::init(); Logger::init();
Logger::setLevel(LogLevel::Debug); Logger::setLevel(LogLevel::Debug);

View File

@ -123,8 +123,7 @@ void GameScene::onUpdate(float dt) {
} }
if (bird_->isLiving() && GAME_HEIGHT - bird_->pos().y <= 123.0f) { if (bird_->isLiving() && GAME_HEIGHT - bird_->pos().y <= 123.0f) {
bird_->setPosition( bird_->setPosition(extra2d::Vec2(bird_->pos().x, GAME_HEIGHT - 123.0f));
extra2d::Vec2(bird_->pos().x, GAME_HEIGHT - 123.0f));
bird_->setStatus(Bird::Status::Still); bird_->setStatus(Bird::Status::Still);
onHit(); onHit();
} }
@ -159,7 +158,7 @@ bool GameScene::checkCollision() {
if (!bird_ || !pipes_) if (!bird_ || !pipes_)
return false; return false;
extra2d::Rect birdBox = bird_->getBoundingBox(); extra2d::Rect birdBox = bird_->boundingBox();
// 检查与每个水管的碰撞 // 检查与每个水管的碰撞
for (int i = 0; i < 3; ++i) { for (int i = 0; i < 3; ++i) {

View File

@ -74,7 +74,7 @@ void StartScene::onEnter() {
playBtn_->setAnchor(0.5f, 0.5f); playBtn_->setAnchor(0.5f, 0.5f);
// PLAY 按钮在小鸟下方 // PLAY 按钮在小鸟下方
playBtn_->setPosition(screenWidth / 2.0f, playBtn_->setPosition(screenWidth / 2.0f,
screenHeight - playBtn_->getSize().height - 100.0f); screenHeight - playBtn_->size().height - 100.0f);
playBtn_->setOnClick([this]() { playBtn_->setOnClick([this]() {
ResLoader::playMusic(MusicType::Click); ResLoader::playMusic(MusicType::Click);
startGame(); startGame();
@ -95,7 +95,7 @@ void StartScene::onEnter() {
shareBtn_->setAnchor(0.5f, 0.5f); shareBtn_->setAnchor(0.5f, 0.5f);
// SHARE 按钮在 PLAY 按钮下方,靠近地面 // SHARE 按钮在 PLAY 按钮下方,靠近地面
shareBtn_->setPosition(screenWidth / 2.0f, shareBtn_->setPosition(screenWidth / 2.0f,
screenHeight - shareBtn_->getSize().height - 80.0f); screenHeight - shareBtn_->size().height - 80.0f);
shareBtn_->setOnClick([this]() { shareBtn_->setOnClick([this]() {
ResLoader::playMusic(MusicType::Click); ResLoader::playMusic(MusicType::Click);
// 分享功能暂不实现 // 分享功能暂不实现

View File

@ -7,9 +7,7 @@
namespace flappybird { namespace flappybird {
Bird::Bird() { Bird::Bird() { setStatus(Status::Idle); }
setStatus(Status::Idle);
}
Bird::~Bird() = default; Bird::~Bird() = default;
@ -28,7 +26,8 @@ void Bird::initAnimations() {
// 加载动画帧序列: 0 -> 1 -> 2 -> 1 // 加载动画帧序列: 0 -> 1 -> 2 -> 1
int frameSequence[] = {0, 1, 2, 1}; int frameSequence[] = {0, 1, 2, 1};
for (int frameIndex : frameSequence) { for (int frameIndex : frameSequence) {
auto frameSprite = ResLoader::getKeyFrame(prefix + std::to_string(frameIndex)); auto frameSprite =
ResLoader::getKeyFrame(prefix + std::to_string(frameIndex));
if (frameSprite) { if (frameSprite) {
frames_.push_back(frameSprite); frames_.push_back(frameSprite);
} else { } else {
@ -41,14 +40,16 @@ void Bird::initAnimations() {
sprite_ = extra2d::Sprite::create(); sprite_ = extra2d::Sprite::create();
setCurrentFrame(0); setCurrentFrame(0);
addChild(sprite_); addChild(sprite_);
E2D_LOG_INFO("小鸟动画创建成功: 颜色={}, 帧数={}", colorMode, frames_.size()); E2D_LOG_INFO("小鸟动画创建成功: 颜色={}, 帧数={}", colorMode,
frames_.size());
} else { } else {
E2D_LOG_ERROR("小鸟动画创建失败: 没有找到任何动画帧"); E2D_LOG_ERROR("小鸟动画创建失败: 没有找到任何动画帧");
} }
} }
void Bird::setCurrentFrame(int frameIndex) { void Bird::setCurrentFrame(int frameIndex) {
if (frames_.empty() || !sprite_) return; if (frames_.empty() || !sprite_)
return;
frameIndex = frameIndex % static_cast<int>(frames_.size()); frameIndex = frameIndex % static_cast<int>(frames_.size());
currentFrame_ = frameIndex; currentFrame_ = frameIndex;
@ -59,7 +60,8 @@ void Bird::setCurrentFrame(int frameIndex) {
} }
void Bird::updateFrameAnimation(float dt) { void Bird::updateFrameAnimation(float dt) {
if (frames_.empty() || status_ == Status::Still) return; if (frames_.empty() || status_ == Status::Still)
return;
frameTimer_ += dt; frameTimer_ += dt;
@ -105,7 +107,8 @@ void Bird::onRender(extra2d::RenderBackend& renderer) {
} }
void Bird::fall(float dt) { void Bird::fall(float dt) {
if (!living_) return; if (!living_)
return;
// 更新垂直位置 // 更新垂直位置
extra2d::Vec2 position = pos(); extra2d::Vec2 position = pos();
@ -132,7 +135,8 @@ void Bird::fall(float dt) {
} }
void Bird::jump() { void Bird::jump() {
if (!living_) return; if (!living_)
return;
// 给小鸟向上的速度 // 给小鸟向上的速度
speed_ = -jumpSpeed; speed_ = -jumpSpeed;
@ -180,16 +184,12 @@ void Bird::setStatus(Status status) {
} }
} }
extra2d::Rect Bird::getBoundingBox() const { extra2d::Rect Bird::boundingBox() const {
extra2d::Vec2 position = pos(); extra2d::Vec2 position = pos();
// 小鸟碰撞框大小约为 24x24 // 小鸟碰撞框大小约为 24x24
float halfSize = 12.0f; float halfSize = 12.0f;
return extra2d::Rect( return extra2d::Rect(position.x - halfSize, position.y - halfSize,
position.x - halfSize, halfSize * 2.0f, halfSize * 2.0f);
position.y - halfSize,
halfSize * 2.0f,
halfSize * 2.0f
);
} }
} // namespace flappybird } // namespace flappybird

View File

@ -90,7 +90,7 @@ public:
* @brief * @brief
* @return * @return
*/ */
extra2d::Rect getBoundingBox() const override; extra2d::Rect boundingBox() const override;
private: private:
/** /**

View File

@ -3,8 +3,9 @@
// ============================================================================ // ============================================================================
#include "Pipe.h" #include "Pipe.h"
#include "ResLoader.h"
#include "BaseScene.h" #include "BaseScene.h"
#include "ResLoader.h"
namespace flappybird { namespace flappybird {
@ -31,12 +32,14 @@ void Pipe::onEnter() {
// 与屏幕底部最小距离不小于地面上方 100 像素 // 与屏幕底部最小距离不小于地面上方 100 像素
float minHeight = 100.0f; float minHeight = 100.0f;
float maxHeight = screenHeight - landHeight - 100.0f - gapHeight_; float maxHeight = screenHeight - landHeight - 100.0f - gapHeight_;
float height = static_cast<float>(extra2d::randomInt(static_cast<int>(minHeight), static_cast<int>(maxHeight))); float height = static_cast<float>(extra2d::randomInt(
static_cast<int>(minHeight), static_cast<int>(maxHeight)));
// 创建上水管 // 创建上水管
auto topFrame = ResLoader::getKeyFrame("pipe_above"); auto topFrame = ResLoader::getKeyFrame("pipe_above");
if (topFrame) { if (topFrame) {
topPipe_ = extra2d::Sprite::create(topFrame->getTexture(), topFrame->getRect()); topPipe_ =
extra2d::Sprite::create(topFrame->getTexture(), topFrame->getRect());
topPipe_->setAnchor(extra2d::Vec2(0.5f, 1.0f)); // 锚点设在底部中心 topPipe_->setAnchor(extra2d::Vec2(0.5f, 1.0f)); // 锚点设在底部中心
topPipe_->setPosition(extra2d::Vec2(0.0f, height - gapHeight_ / 2.0f)); topPipe_->setPosition(extra2d::Vec2(0.0f, height - gapHeight_ / 2.0f));
addChild(topPipe_); addChild(topPipe_);
@ -45,7 +48,8 @@ void Pipe::onEnter() {
// 创建下水管 // 创建下水管
auto bottomFrame = ResLoader::getKeyFrame("pipe_below"); auto bottomFrame = ResLoader::getKeyFrame("pipe_below");
if (bottomFrame) { if (bottomFrame) {
bottomPipe_ = extra2d::Sprite::create(bottomFrame->getTexture(), bottomFrame->getRect()); bottomPipe_ = extra2d::Sprite::create(bottomFrame->getTexture(),
bottomFrame->getRect());
bottomPipe_->setAnchor(extra2d::Vec2(0.5f, 0.0f)); // 锚点设在顶部中心 bottomPipe_->setAnchor(extra2d::Vec2(0.5f, 0.0f)); // 锚点设在顶部中心
bottomPipe_->setPosition(extra2d::Vec2(0.0f, height + gapHeight_ / 2.0f)); bottomPipe_->setPosition(extra2d::Vec2(0.0f, height + gapHeight_ / 2.0f));
addChild(bottomPipe_); addChild(bottomPipe_);
@ -55,7 +59,7 @@ void Pipe::onEnter() {
Pipe::~Pipe() = default; Pipe::~Pipe() = default;
extra2d::Rect Pipe::getBoundingBox() const { extra2d::Rect Pipe::boundingBox() const {
// 返回整个水管的边界框(包含上下两根) // 返回整个水管的边界框(包含上下两根)
extra2d::Vec2 position = pos(); extra2d::Vec2 position = pos();
@ -66,16 +70,12 @@ extra2d::Rect Pipe::getBoundingBox() const {
// 使用游戏逻辑高度 // 使用游戏逻辑高度
float screenHeight = GAME_HEIGHT; float screenHeight = GAME_HEIGHT;
return extra2d::Rect( return extra2d::Rect(position.x - halfWidth, 0.0f, pipeWidth, screenHeight);
position.x - halfWidth,
0.0f,
pipeWidth,
screenHeight
);
} }
extra2d::Rect Pipe::getTopPipeBox() const { extra2d::Rect Pipe::getTopPipeBox() const {
if (!topPipe_) return extra2d::Rect(); if (!topPipe_)
return extra2d::Rect();
extra2d::Vec2 position = pos(); extra2d::Vec2 position = pos();
extra2d::Vec2 topPos = topPipe_->pos(); extra2d::Vec2 topPos = topPipe_->pos();
@ -84,16 +84,14 @@ extra2d::Rect Pipe::getTopPipeBox() const {
float pipeWidth = 52.0f; float pipeWidth = 52.0f;
float pipeHeight = 320.0f; float pipeHeight = 320.0f;
return extra2d::Rect( return extra2d::Rect(position.x - pipeWidth / 2.0f,
position.x - pipeWidth / 2.0f, position.y + topPos.y - pipeHeight, pipeWidth,
position.y + topPos.y - pipeHeight, pipeHeight);
pipeWidth,
pipeHeight
);
} }
extra2d::Rect Pipe::getBottomPipeBox() const { extra2d::Rect Pipe::getBottomPipeBox() const {
if (!bottomPipe_) return extra2d::Rect(); if (!bottomPipe_)
return extra2d::Rect();
extra2d::Vec2 position = pos(); extra2d::Vec2 position = pos();
extra2d::Vec2 bottomPos = bottomPipe_->pos(); extra2d::Vec2 bottomPos = bottomPipe_->pos();
@ -102,12 +100,8 @@ extra2d::Rect Pipe::getBottomPipeBox() const {
float pipeWidth = 52.0f; float pipeWidth = 52.0f;
float pipeHeight = 320.0f; float pipeHeight = 320.0f;
return extra2d::Rect( return extra2d::Rect(position.x - pipeWidth / 2.0f, position.y + bottomPos.y,
position.x - pipeWidth / 2.0f, pipeWidth, pipeHeight);
position.y + bottomPos.y,
pipeWidth,
pipeHeight
);
} }
} // namespace flappybird } // namespace flappybird

View File

@ -34,7 +34,7 @@ public:
* @brief * @brief
* @return * @return
*/ */
extra2d::Rect getBoundingBox() const override; extra2d::Rect boundingBox() const override;
/** /**
* @brief * @brief

View File

@ -37,8 +37,8 @@ public:
bool isColliding() const { return isColliding_; } bool isColliding() const { return isColliding_; }
int getId() const { return id_; } int getId() const { return id_; }
// 必须实现 getBoundingBox() 才能参与空间索引碰撞检测 // 必须实现 boundingBox() 才能参与空间索引碰撞检测
Rect getBoundingBox() const override { Rect boundingBox() const override {
Vec2 position = pos(); Vec2 position = pos();
return Rect(position.x - size_ / 2, position.y - size_ / 2, size_, size_); return Rect(position.x - size_ / 2, position.y - size_ / 2, size_, size_);
} }
@ -65,13 +65,15 @@ public:
// 碰撞时变红色 // 碰撞时变红色
Color fillColor = isColliding_ ? Color(1.0f, 0.2f, 0.2f, 0.9f) : color_; Color fillColor = isColliding_ ? Color(1.0f, 0.2f, 0.2f, 0.9f) : color_;
renderer.fillRect(Rect(position.x - size_ / 2, position.y - size_ / 2, size_, size_), renderer.fillRect(
Rect(position.x - size_ / 2, position.y - size_ / 2, size_, size_),
fillColor); fillColor);
// 绘制边框 // 绘制边框
Color borderColor = isColliding_ ? Color(1.0f, 0.0f, 0.0f, 1.0f) Color borderColor = isColliding_ ? Color(1.0f, 0.0f, 0.0f, 1.0f)
: Color(0.3f, 0.3f, 0.3f, 0.5f); : Color(0.3f, 0.3f, 0.3f, 0.5f);
renderer.drawRect(Rect(position.x - size_ / 2, position.y - size_ / 2, size_, size_), renderer.drawRect(
Rect(position.x - size_ / 2, position.y - size_ / 2, size_, size_),
borderColor, 1.0f); borderColor, 1.0f);
} }

View File

@ -30,7 +30,7 @@ public:
/// 获取遮罩尺寸 /// 获取遮罩尺寸
int getWidth() const { return width_; } int getWidth() const { return width_; }
int getHeight() const { return height_; } int getHeight() const { return height_; }
Size getSize() const { Size size() const {
return Size(static_cast<float>(width_), static_cast<float>(height_)); return Size(static_cast<float>(width_), static_cast<float>(height_));
} }

View File

@ -1,7 +1,8 @@
#pragma once #pragma once
#include <graphics/texture.h>
#include <graphics/alpha_mask.h> #include <graphics/alpha_mask.h>
#include <graphics/texture.h>
#include <glad/glad.h> #include <glad/glad.h>
@ -22,10 +23,14 @@ public:
// Texture 接口实现 // Texture 接口实现
int getWidth() const override { return width_; } int getWidth() const override { return width_; }
int getHeight() const override { return height_; } int getHeight() const override { return height_; }
Size getSize() const override { return Size(static_cast<float>(width_), static_cast<float>(height_)); } Size size() const override {
return Size(static_cast<float>(width_), static_cast<float>(height_));
}
int getChannels() const override { return channels_; } int getChannels() const override { return channels_; }
PixelFormat getFormat() const override; PixelFormat getFormat() const override;
void* getNativeHandle() const override { return reinterpret_cast<void*>(static_cast<uintptr_t>(textureID_)); } void *getNativeHandle() const override {
return reinterpret_cast<void *>(static_cast<uintptr_t>(textureID_));
}
bool isValid() const override { return textureID_ != 0; } bool isValid() const override { return textureID_ != 0; }
void setFilter(bool linear) override; void setFilter(bool linear) override;
void setWrap(bool repeat) override; void setWrap(bool repeat) override;
@ -45,7 +50,9 @@ public:
size_t getDataSize() const { return dataSize_; } size_t getDataSize() const { return dataSize_; }
// Alpha 遮罩 // Alpha 遮罩
bool hasAlphaMask() const { return alphaMask_ != nullptr && alphaMask_->isValid(); } bool hasAlphaMask() const {
return alphaMask_ != nullptr && alphaMask_->isValid();
}
const AlphaMask *getAlphaMask() const { return alphaMask_.get(); } const AlphaMask *getAlphaMask() const { return alphaMask_.get(); }
void generateAlphaMask(); // 从当前纹理数据生成遮罩 void generateAlphaMask(); // 从当前纹理数据生成遮罩

View File

@ -78,7 +78,7 @@ public:
int getWidth() const { return width_; } int getWidth() const { return width_; }
int getHeight() const { return height_; } int getHeight() const { return height_; }
Vec2 getSize() const { Vec2 size() const {
return Vec2(static_cast<float>(width_), static_cast<float>(height_)); return Vec2(static_cast<float>(width_), static_cast<float>(height_));
} }
PixelFormat getColorFormat() const { return colorFormat_; } PixelFormat getColorFormat() const { return colorFormat_; }

View File

@ -1,7 +1,8 @@
#pragma once #pragma once
#include <core/types.h>
#include <core/math_types.h> #include <core/math_types.h>
#include <core/types.h>
namespace extra2d { namespace extra2d {
@ -40,7 +41,7 @@ public:
// 获取尺寸 // 获取尺寸
virtual int getWidth() const = 0; virtual int getWidth() const = 0;
virtual int getHeight() const = 0; virtual int getHeight() const = 0;
virtual Size getSize() const = 0; virtual Size size() const = 0;
// 获取通道数 // 获取通道数
virtual int getChannels() const = 0; virtual int getChannels() const = 0;

View File

@ -1,10 +1,11 @@
#pragma once #pragma once
#include <core/types.h>
#include <core/string.h>
#include <core/math_types.h> #include <core/math_types.h>
#include <core/string.h>
#include <core/types.h>
#include <functional> #include <functional>
#include <SDL.h> #include <SDL.h>
namespace extra2d { namespace extra2d {
@ -27,7 +28,8 @@ struct WindowConfig {
bool centerWindow = true; bool centerWindow = true;
bool enableCursors = true; bool enableCursors = true;
bool enableDpiScale = true; bool enableDpiScale = true;
bool fullscreenDesktop = true; // true: SDL_WINDOW_FULLSCREEN_DESKTOP, false: SDL_WINDOW_FULLSCREEN bool fullscreenDesktop =
true; // true: SDL_WINDOW_FULLSCREEN_DESKTOP, false: SDL_WINDOW_FULLSCREEN
}; };
// ============================================================================ // ============================================================================
@ -75,7 +77,9 @@ public:
// 获取窗口属性 // 获取窗口属性
int getWidth() const { return width_; } int getWidth() const { return width_; }
int getHeight() const { return height_; } int getHeight() const { return height_; }
Size getSize() const { return Size(static_cast<float>(width_), static_cast<float>(height_)); } Size size() const {
return Size(static_cast<float>(width_), static_cast<float>(height_));
}
Vec2 pos() const; Vec2 pos() const;
bool isFullscreen() const { return fullscreen_; } bool isFullscreen() const { return fullscreen_; }
bool isVSync() const { return vsync_; } bool isVSync() const { return vsync_; }
@ -115,7 +119,9 @@ public:
using FocusCallback = std::function<void(bool focused)>; using FocusCallback = std::function<void(bool focused)>;
using CloseCallback = std::function<void()>; using CloseCallback = std::function<void()>;
void setResizeCallback(ResizeCallback callback) { resizeCallback_ = callback; } void setResizeCallback(ResizeCallback callback) {
resizeCallback_ = callback;
}
void setFocusCallback(FocusCallback callback) { focusCallback_ = callback; } void setFocusCallback(FocusCallback callback) { focusCallback_ = callback; }
void setCloseCallback(CloseCallback callback) { closeCallback_ = callback; } void setCloseCallback(CloseCallback callback) { closeCallback_ = callback; }

View File

@ -5,12 +5,13 @@
#include <core/math_types.h> #include <core/math_types.h>
#include <core/types.h> #include <core/types.h>
#include <event/event_dispatcher.h> #include <event/event_dispatcher.h>
#include <graphics/render_backend.h>
#include <functional> #include <functional>
#include <graphics/render_backend.h>
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
namespace extra2d { namespace extra2d {
// 前向声明 // 前向声明
@ -148,7 +149,7 @@ public:
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// 边界框(用于空间索引) // 边界框(用于空间索引)
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
virtual Rect getBoundingBox() const; virtual Rect boundingBox() const;
// 是否需要参与空间索引(默认 true // 是否需要参与空间索引(默认 true
void setSpatialIndexed(bool indexed) { spatialIndexed_ = indexed; } void setSpatialIndexed(bool indexed) { spatialIndexed_ = indexed; }
@ -216,12 +217,14 @@ public:
/** /**
* @brief 1 * @brief 1
*/ */
Tween &fadeIn(float duration, TweenEasing easing = static_cast<TweenEasing>(0)); Tween &fadeIn(float duration,
TweenEasing easing = static_cast<TweenEasing>(0));
/** /**
* @brief 0 * @brief 0
*/ */
Tween &fadeOut(float duration, TweenEasing easing = static_cast<TweenEasing>(0)); Tween &fadeOut(float duration,
TweenEasing easing = static_cast<TweenEasing>(0));
/** /**
* @brief * @brief

View File

@ -85,7 +85,7 @@ public:
void addPoint(const Vec2 &point); void addPoint(const Vec2 &point);
void clearPoints(); void clearPoints();
Rect getBoundingBox() const override; Rect boundingBox() const override;
protected: protected:
void onDraw(RenderBackend &renderer) override; void onDraw(RenderBackend &renderer) override;

View File

@ -37,7 +37,7 @@ public:
static Ptr<Sprite> create(Ptr<Texture> texture); static Ptr<Sprite> create(Ptr<Texture> texture);
static Ptr<Sprite> create(Ptr<Texture> texture, const Rect &rect); static Ptr<Sprite> create(Ptr<Texture> texture, const Rect &rect);
Rect getBoundingBox() const override; Rect boundingBox() const override;
protected: protected:
void onDraw(RenderBackend &renderer) override; void onDraw(RenderBackend &renderer) override;

View File

@ -178,7 +178,7 @@ public:
*/ */
void setStateTextColor(const Color &colorOff, const Color &colorOn); void setStateTextColor(const Color &colorOff, const Color &colorOn);
Rect getBoundingBox() const override; Rect boundingBox() const override;
protected: protected:
void onDrawWidget(RenderBackend &renderer) override; void onDrawWidget(RenderBackend &renderer) override;

View File

@ -71,7 +71,7 @@ public:
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
void setOnStateChange(Function<void(bool)> callback); void setOnStateChange(Function<void(bool)> callback);
Rect getBoundingBox() const override; Rect boundingBox() const override;
protected: protected:
void onDrawWidget(RenderBackend &renderer) override; void onDrawWidget(RenderBackend &renderer) override;

View File

@ -108,7 +108,7 @@ public:
Vec2 getTextSize() const; Vec2 getTextSize() const;
float getLineHeight() const; float getLineHeight() const;
Rect getBoundingBox() const override; Rect boundingBox() const override;
protected: protected:
void onDrawWidget(RenderBackend &renderer) override; void onDrawWidget(RenderBackend &renderer) override;
@ -138,7 +138,8 @@ private:
mutable bool sizeDirty_ = true; mutable bool sizeDirty_ = true;
void updateCache() const; void updateCache() const;
void drawText(RenderBackend &renderer, const Vec2 &position, const Color &color); void drawText(RenderBackend &renderer, const Vec2 &position,
const Color &color);
Vec2 calculateDrawPosition() const; Vec2 calculateDrawPosition() const;
std::vector<std::string> splitLines() const; std::vector<std::string> splitLines() const;
}; };

View File

@ -147,7 +147,7 @@ public:
void setStripeSpeed(float speed); // 条纹移动速度 void setStripeSpeed(float speed); // 条纹移动速度
float getStripeSpeed() const { return stripeSpeed_; } float getStripeSpeed() const { return stripeSpeed_; }
Rect getBoundingBox() const override; Rect boundingBox() const override;
protected: protected:
void onUpdate(float deltaTime) override; void onUpdate(float deltaTime) override;
@ -210,8 +210,10 @@ private:
Color getCurrentFillColor() const; Color getCurrentFillColor() const;
std::string formatText() const; std::string formatText() const;
void drawRoundedRect(RenderBackend &renderer, const Rect &rect, const Color &color, float radius); void drawRoundedRect(RenderBackend &renderer, const Rect &rect,
void fillRoundedRect(RenderBackend &renderer, const Rect &rect, const Color &color, float radius); const Color &color, float radius);
void fillRoundedRect(RenderBackend &renderer, const Rect &rect,
const Color &color, float radius);
void drawStripes(RenderBackend &renderer, const Rect &rect); void drawStripes(RenderBackend &renderer, const Rect &rect);
}; };

View File

@ -76,7 +76,7 @@ public:
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
void setOnStateChange(Function<void(bool)> callback); void setOnStateChange(Function<void(bool)> callback);
Rect getBoundingBox() const override; Rect boundingBox() const override;
protected: protected:
void onDrawWidget(RenderBackend &renderer) override; void onDrawWidget(RenderBackend &renderer) override;

View File

@ -103,7 +103,7 @@ public:
void setOnDragStart(Function<void()> callback); void setOnDragStart(Function<void()> callback);
void setOnDragEnd(Function<void()> callback); void setOnDragEnd(Function<void()> callback);
Rect getBoundingBox() const override; Rect boundingBox() const override;
protected: protected:
void onDrawWidget(RenderBackend &renderer) override; void onDrawWidget(RenderBackend &renderer) override;

View File

@ -2,11 +2,12 @@
#include <core/color.h> #include <core/color.h>
#include <core/types.h> #include <core/types.h>
#include <graphics/font.h>
#include <ui/widget.h>
#include <cstdarg> #include <cstdarg>
#include <cstdio> #include <cstdio>
#include <graphics/font.h>
#include <string> #include <string>
#include <ui/widget.h>
namespace extra2d { namespace extra2d {
@ -98,7 +99,7 @@ public:
Vec2 getTextSize() const; Vec2 getTextSize() const;
float getLineHeight() const; float getLineHeight() const;
Rect getBoundingBox() const override; Rect boundingBox() const override;
protected: protected:
void onDrawWidget(RenderBackend &renderer) override; void onDrawWidget(RenderBackend &renderer) override;

View File

@ -27,9 +27,9 @@ public:
void setSize(const Size &size); void setSize(const Size &size);
void setSize(float width, float height); void setSize(float width, float height);
Size getSize() const { return size_; } Size size() const { return size_; }
Rect getBoundingBox() const override; Rect boundingBox() const override;
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// 鼠标事件处理(子类可重写) // 鼠标事件处理(子类可重写)
@ -55,7 +55,7 @@ public:
protected: protected:
// 供子类使用的辅助方法 // 供子类使用的辅助方法
bool isPointInside(float x, float y) const { bool isPointInside(float x, float y) const {
return getBoundingBox().containsPoint(Point(x, y)); return boundingBox().containsPoint(Point(x, y));
} }
// 子类重写此方法以支持自定义渲染 // 子类重写此方法以支持自定义渲染

View File

@ -1,18 +1,17 @@
#include <algorithm> #include <algorithm>
#include <cmath>
#include <animation/tween.h> #include <animation/tween.h>
#include <cmath>
#include <graphics/render_command.h> #include <graphics/render_command.h>
#include <scene/node.h> #include <scene/node.h>
#include <scene/scene.h> #include <scene/scene.h>
#include <utils/logger.h> #include <utils/logger.h>
namespace extra2d { namespace extra2d {
Node::Node() = default; Node::Node() = default;
Node::~Node() { Node::~Node() { removeAllChildren(); }
removeAllChildren();
}
void Node::addChild(Ptr<Node> child) { void Node::addChild(Ptr<Node> child) {
if (!child || child.get() == this) { if (!child || child.get() == this) {
@ -384,7 +383,7 @@ void Node::onDetachFromScene() {
} }
} }
Rect Node::getBoundingBox() const { Rect Node::boundingBox() const {
// 默认返回一个以位置为中心的点矩形 // 默认返回一个以位置为中心的点矩形
return Rect(position_.x, position_.y, 0, 0); return Rect(position_.x, position_.y, 0, 0);
} }
@ -394,7 +393,7 @@ void Node::updateSpatialIndex() {
return; return;
} }
Rect newBounds = getBoundingBox(); Rect newBounds = boundingBox();
if (newBounds != lastSpatialBounds_) { if (newBounds != lastSpatialBounds_) {
scene_->updateNodeInSpatialIndex(this, lastSpatialBounds_, newBounds); scene_->updateNodeInSpatialIndex(this, lastSpatialBounds_, newBounds);
lastSpatialBounds_ = newBounds; lastSpatialBounds_ = newBounds;

View File

@ -37,7 +37,7 @@ Node *hitTestTopmost(const Ptr<Node> &node, const Vec2 &worldPos) {
return nullptr; return nullptr;
} }
Rect bounds = node->getBoundingBox(); Rect bounds = node->boundingBox();
if (!bounds.empty() && bounds.containsPoint(worldPos)) { if (!bounds.empty() && bounds.containsPoint(worldPos)) {
return node.get(); return node.get();
} }

View File

@ -2,8 +2,9 @@
#include <cmath> #include <cmath>
#include <graphics/render_backend.h> #include <graphics/render_backend.h>
#include <graphics/render_command.h> #include <graphics/render_command.h>
#include <scene/shape_node.h>
#include <limits> #include <limits>
#include <scene/shape_node.h>
namespace extra2d { namespace extra2d {
@ -124,7 +125,7 @@ void ShapeNode::clearPoints() {
updateSpatialIndex(); updateSpatialIndex();
} }
Rect ShapeNode::getBoundingBox() const { Rect ShapeNode::boundingBox() const {
if (points_.empty()) { if (points_.empty()) {
return Rect(); return Rect();
} }
@ -262,16 +263,16 @@ void ShapeNode::generateRenderCommand(std::vector<RenderCommand> &commands,
case ShapeType::Point: case ShapeType::Point:
if (!points_.empty()) { if (!points_.empty()) {
cmd.type = RenderCommandType::FilledCircle; cmd.type = RenderCommandType::FilledCircle;
cmd.data = cmd.data = CircleCommandData{
CircleCommandData{points_[0] + offset, lineWidth_ * 0.5f, color_, 8, 0.0f, true}; points_[0] + offset, lineWidth_ * 0.5f, color_, 8, 0.0f, true};
} }
break; break;
case ShapeType::Line: case ShapeType::Line:
if (points_.size() >= 2) { if (points_.size() >= 2) {
cmd.type = RenderCommandType::Line; cmd.type = RenderCommandType::Line;
cmd.data = LineCommandData{points_[0] + offset, points_[1] + offset, color_, cmd.data = LineCommandData{points_[0] + offset, points_[1] + offset,
lineWidth_}; color_, lineWidth_};
} }
break; break;
@ -281,14 +282,14 @@ void ShapeNode::generateRenderCommand(std::vector<RenderCommand> &commands,
cmd.type = RenderCommandType::FilledRect; cmd.type = RenderCommandType::FilledRect;
Rect rect(points_[0].x, points_[0].y, points_[2].x - points_[0].x, Rect rect(points_[0].x, points_[0].y, points_[2].x - points_[0].x,
points_[2].y - points_[0].y); points_[2].y - points_[0].y);
cmd.data = cmd.data = RectCommandData{Rect(rect.origin + offset, rect.size),
RectCommandData{Rect(rect.origin + offset, rect.size), color_, 0.0f, true}; color_, 0.0f, true};
} else { } else {
cmd.type = RenderCommandType::Rect; cmd.type = RenderCommandType::Rect;
Rect rect(points_[0].x, points_[0].y, points_[2].x - points_[0].x, Rect rect(points_[0].x, points_[0].y, points_[2].x - points_[0].x,
points_[2].y - points_[0].y); points_[2].y - points_[0].y);
cmd.data = cmd.data = RectCommandData{Rect(rect.origin + offset, rect.size),
RectCommandData{Rect(rect.origin + offset, rect.size), color_, lineWidth_, false}; color_, lineWidth_, false};
} }
} }
break; break;
@ -298,12 +299,12 @@ void ShapeNode::generateRenderCommand(std::vector<RenderCommand> &commands,
float radius = points_[1].x; float radius = points_[1].x;
if (filled_) { if (filled_) {
cmd.type = RenderCommandType::FilledCircle; cmd.type = RenderCommandType::FilledCircle;
cmd.data = cmd.data = CircleCommandData{points_[0] + offset, radius, color_,
CircleCommandData{points_[0] + offset, radius, color_, segments_, 0.0f, true}; segments_, 0.0f, true};
} else { } else {
cmd.type = RenderCommandType::Circle; cmd.type = RenderCommandType::Circle;
cmd.data = CircleCommandData{points_[0] + offset, radius, color_, segments_, cmd.data = CircleCommandData{points_[0] + offset, radius, color_,
lineWidth_, false}; segments_, lineWidth_, false};
} }
} }
break; break;
@ -336,7 +337,8 @@ void ShapeNode::generateRenderCommand(std::vector<RenderCommand> &commands,
cmd.data = PolygonCommandData{transformedPoints, color_, 0.0f, true}; cmd.data = PolygonCommandData{transformedPoints, color_, 0.0f, true};
} else { } else {
cmd.type = RenderCommandType::Polygon; cmd.type = RenderCommandType::Polygon;
cmd.data = PolygonCommandData{transformedPoints, color_, lineWidth_, false}; cmd.data =
PolygonCommandData{transformedPoints, color_, lineWidth_, false};
} }
} }
break; break;

View File

@ -43,7 +43,7 @@ Ptr<Sprite> Sprite::create(Ptr<Texture> texture, const Rect &rect) {
return sprite; return sprite;
} }
Rect Sprite::getBoundingBox() const { Rect Sprite::boundingBox() const {
if (!texture_ || !texture_->isValid()) { if (!texture_ || !texture_->isValid()) {
return Rect(); return Rect();
} }

View File

@ -130,7 +130,7 @@ void SpatialManager::rebuild() {
auto objects = oldIndex->query(bounds); auto objects = oldIndex->query(bounds);
for (Node *node : objects) { for (Node *node : objects) {
if (node) { if (node) {
auto nodeBounds = node->getBoundingBox(); auto nodeBounds = node->boundingBox();
index_->insert(node, nodeBounds); index_->insert(node, nodeBounds);
} }
} }

View File

@ -1,6 +1,6 @@
#include <algorithm> #include <algorithm>
#include <cmath>
#include <app/application.h> #include <app/application.h>
#include <cmath>
#include <core/string.h> #include <core/string.h>
#include <graphics/render_backend.h> #include <graphics/render_backend.h>
#include <ui/button.h> #include <ui/button.h>
@ -93,7 +93,7 @@ Ptr<Button> Button::create(const std::string &text, Ptr<FontAtlas> font) {
*/ */
void Button::setText(const std::string &text) { void Button::setText(const std::string &text) {
text_ = text; text_ = text;
if (font_ && getSize().empty()) { if (font_ && size().empty()) {
Vec2 textSize = font_->measureText(text_); Vec2 textSize = font_->measureText(text_);
setSize(textSize.x + padding_.x * 2.0f, textSize.y + padding_.y * 2.0f); setSize(textSize.x + padding_.x * 2.0f, textSize.y + padding_.y * 2.0f);
} }
@ -105,7 +105,7 @@ void Button::setText(const std::string &text) {
*/ */
void Button::setFont(Ptr<FontAtlas> font) { void Button::setFont(Ptr<FontAtlas> font) {
font_ = font; font_ = font;
if (font_ && getSize().empty() && !text_.empty()) { if (font_ && size().empty() && !text_.empty()) {
Vec2 textSize = font_->measureText(text_); Vec2 textSize = font_->measureText(text_);
setSize(textSize.x + padding_.x * 2.0f, textSize.y + padding_.y * 2.0f); setSize(textSize.x + padding_.x * 2.0f, textSize.y + padding_.y * 2.0f);
} }
@ -117,7 +117,7 @@ void Button::setFont(Ptr<FontAtlas> font) {
*/ */
void Button::setPadding(const Vec2 &padding) { void Button::setPadding(const Vec2 &padding) {
padding_ = padding; padding_ = padding;
if (font_ && getSize().empty() && !text_.empty()) { if (font_ && size().empty() && !text_.empty()) {
Vec2 textSize = font_->measureText(text_); Vec2 textSize = font_->measureText(text_);
setSize(textSize.x + padding_.x * 2.0f, textSize.y + padding_.y * 2.0f); setSize(textSize.x + padding_.x * 2.0f, textSize.y + padding_.y * 2.0f);
} }
@ -128,9 +128,7 @@ void Button::setPadding(const Vec2 &padding) {
* @param x X方向内边距 * @param x X方向内边距
* @param y Y方向内边距 * @param y Y方向内边距
*/ */
void Button::setPadding(float x, float y) { void Button::setPadding(float x, float y) { setPadding(Vec2(x, y)); }
setPadding(Vec2(x, y));
}
/** /**
* @brief * @brief
@ -356,20 +354,20 @@ void Button::setCustomSize(float width, float height) {
* @brief * @brief
* @return * @return
*/ */
Rect Button::getBoundingBox() const { Rect Button::boundingBox() const {
auto position = convertToWorldSpace(extra2d::Vec2::Zero()); auto position = convertToWorldSpace(extra2d::Vec2::Zero());
auto anchorPt = anchor(); auto anchorPt = anchor();
auto scaleVal = scale(); auto scaleVal = scale();
auto size = getSize(); auto widgetSize = size();
if (size.empty()) { if (widgetSize.empty()) {
return Rect(); return Rect();
} }
float w = size.width * scaleVal.x; float w = widgetSize.width * scaleVal.x;
float h = size.height * scaleVal.y; float h = widgetSize.height * scaleVal.y;
float x0 = position.x - size.width * anchorPt.x * scaleVal.x; float x0 = position.x - widgetSize.width * anchorPt.x * scaleVal.x;
float y0 = position.y - size.height * anchorPt.y * scaleVal.y; float y0 = position.y - widgetSize.height * anchorPt.y * scaleVal.y;
return Rect(x0, y0, w, h); return Rect(x0, y0, w, h);
} }
@ -616,7 +614,7 @@ void Button::fillRoundedRect(RenderBackend &renderer, const Rect &rect,
* @param renderer * @param renderer
*/ */
void Button::onDrawWidget(RenderBackend &renderer) { void Button::onDrawWidget(RenderBackend &renderer) {
Rect rect = getBoundingBox(); Rect rect = boundingBox();
if (rect.empty()) { if (rect.empty()) {
return; return;
} }

View File

@ -1,6 +1,6 @@
#include <ui/check_box.h>
#include <graphics/render_backend.h>
#include <core/string.h> #include <core/string.h>
#include <graphics/render_backend.h>
#include <ui/check_box.h>
namespace extra2d { namespace extra2d {
@ -16,9 +16,7 @@ CheckBox::CheckBox() {
* @brief * @brief
* @return * @return
*/ */
Ptr<CheckBox> CheckBox::create() { Ptr<CheckBox> CheckBox::create() { return makePtr<CheckBox>(); }
return makePtr<CheckBox>();
}
/** /**
* @brief * @brief
@ -47,57 +45,43 @@ void CheckBox::setChecked(bool checked) {
/** /**
* @brief * @brief
*/ */
void CheckBox::toggle() { void CheckBox::toggle() { setChecked(!checked_); }
setChecked(!checked_);
}
/** /**
* @brief * @brief
* @param label * @param label
*/ */
void CheckBox::setLabel(const std::string &label) { void CheckBox::setLabel(const std::string &label) { label_ = label; }
label_ = label;
}
/** /**
* @brief * @brief
* @param font * @param font
*/ */
void CheckBox::setFont(Ptr<FontAtlas> font) { void CheckBox::setFont(Ptr<FontAtlas> font) { font_ = font; }
font_ = font;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void CheckBox::setTextColor(const Color &color) { void CheckBox::setTextColor(const Color &color) { textColor_ = color; }
textColor_ = color;
}
/** /**
* @brief * @brief
* @param size * @param size
*/ */
void CheckBox::setBoxSize(float size) { void CheckBox::setBoxSize(float size) { boxSize_ = size; }
boxSize_ = size;
}
/** /**
* @brief * @brief
* @param spacing * @param spacing
*/ */
void CheckBox::setSpacing(float spacing) { void CheckBox::setSpacing(float spacing) { spacing_ = spacing; }
spacing_ = spacing;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void CheckBox::setCheckedColor(const Color &color) { void CheckBox::setCheckedColor(const Color &color) { checkedColor_ = color; }
checkedColor_ = color;
}
/** /**
* @brief * @brief
@ -127,7 +111,7 @@ void CheckBox::setOnStateChange(Function<void(bool)> callback) {
* @brief * @brief
* @return * @return
*/ */
Rect CheckBox::getBoundingBox() const { Rect CheckBox::boundingBox() const {
Vec2 position = pos(); Vec2 position = pos();
float width = boxSize_; float width = boxSize_;
@ -146,7 +130,8 @@ Rect CheckBox::getBoundingBox() const {
void CheckBox::onDrawWidget(RenderBackend &renderer) { void CheckBox::onDrawWidget(RenderBackend &renderer) {
Vec2 position = pos(); Vec2 position = pos();
Rect boxRect(position.x, position.y + (getSize().height - boxSize_) * 0.5f, boxSize_, boxSize_); Rect boxRect(position.x, position.y + (size().height - boxSize_) * 0.5f,
boxSize_, boxSize_);
Color boxColor = checked_ ? checkedColor_ : uncheckedColor_; Color boxColor = checked_ ? checkedColor_ : uncheckedColor_;
renderer.fillRect(boxRect, boxColor); renderer.fillRect(boxRect, boxColor);
renderer.drawRect(boxRect, Colors::White, 1.0f); renderer.drawRect(boxRect, Colors::White, 1.0f);

View File

@ -1,15 +1,13 @@
#include <ui/label.h>
#include <graphics/render_backend.h>
#include <core/string.h> #include <core/string.h>
#include <graphics/render_backend.h>
#include <ui/label.h>
namespace extra2d { namespace extra2d {
/** /**
* @brief * @brief
*/ */
Label::Label() { Label::Label() { setAnchor(0.0f, 0.0f); }
setAnchor(0.0f, 0.0f);
}
/** /**
* @brief * @brief
@ -24,9 +22,7 @@ Label::Label(const std::string &text) : text_(text) {
* @brief * @brief
* @return * @return
*/ */
Ptr<Label> Label::create() { Ptr<Label> Label::create() { return makePtr<Label>(); }
return makePtr<Label>();
}
/** /**
* @brief * @brief
@ -73,9 +69,7 @@ void Label::setFont(Ptr<FontAtlas> font) {
* @brief * @brief
* @param color * @param color
*/ */
void Label::setTextColor(const Color &color) { void Label::setTextColor(const Color &color) { textColor_ = color; }
textColor_ = color;
}
/** /**
* @brief * @brief
@ -91,65 +85,49 @@ void Label::setFontSize(int size) {
* @brief * @brief
* @param align * @param align
*/ */
void Label::setHorizontalAlign(HorizontalAlign align) { void Label::setHorizontalAlign(HorizontalAlign align) { hAlign_ = align; }
hAlign_ = align;
}
/** /**
* @brief * @brief
* @param align * @param align
*/ */
void Label::setVerticalAlign(VerticalAlign align) { void Label::setVerticalAlign(VerticalAlign align) { vAlign_ = align; }
vAlign_ = align;
}
/** /**
* @brief * @brief
* @param enabled * @param enabled
*/ */
void Label::setShadowEnabled(bool enabled) { void Label::setShadowEnabled(bool enabled) { shadowEnabled_ = enabled; }
shadowEnabled_ = enabled;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void Label::setShadowColor(const Color &color) { void Label::setShadowColor(const Color &color) { shadowColor_ = color; }
shadowColor_ = color;
}
/** /**
* @brief * @brief
* @param offset * @param offset
*/ */
void Label::setShadowOffset(const Vec2 &offset) { void Label::setShadowOffset(const Vec2 &offset) { shadowOffset_ = offset; }
shadowOffset_ = offset;
}
/** /**
* @brief * @brief
* @param enabled * @param enabled
*/ */
void Label::setOutlineEnabled(bool enabled) { void Label::setOutlineEnabled(bool enabled) { outlineEnabled_ = enabled; }
outlineEnabled_ = enabled;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void Label::setOutlineColor(const Color &color) { void Label::setOutlineColor(const Color &color) { outlineColor_ = color; }
outlineColor_ = color;
}
/** /**
* @brief * @brief
* @param width * @param width
*/ */
void Label::setOutlineWidth(float width) { void Label::setOutlineWidth(float width) { outlineWidth_ = width; }
outlineWidth_ = width;
}
/** /**
* @brief * @brief
@ -306,18 +284,18 @@ std::vector<std::string> Label::splitLines() const {
*/ */
Vec2 Label::calculateDrawPosition() const { Vec2 Label::calculateDrawPosition() const {
Vec2 position = pos(); Vec2 position = pos();
Vec2 size = getTextSize(); Vec2 textSize = getTextSize();
Size widgetSize = getSize(); Size widgetSize = size();
float refWidth = widgetSize.empty() ? size.x : widgetSize.width; float refWidth = widgetSize.empty() ? textSize.x : widgetSize.width;
float refHeight = widgetSize.empty() ? size.y : widgetSize.height; float refHeight = widgetSize.empty() ? textSize.y : widgetSize.height;
switch (hAlign_) { switch (hAlign_) {
case HorizontalAlign::Center: case HorizontalAlign::Center:
position.x += (refWidth - size.x) * 0.5f; position.x += (refWidth - textSize.x) * 0.5f;
break; break;
case HorizontalAlign::Right: case HorizontalAlign::Right:
position.x += refWidth - size.x; position.x += refWidth - textSize.x;
break; break;
case HorizontalAlign::Left: case HorizontalAlign::Left:
default: default:
@ -326,10 +304,10 @@ Vec2 Label::calculateDrawPosition() const {
switch (vAlign_) { switch (vAlign_) {
case VerticalAlign::Middle: case VerticalAlign::Middle:
position.y += (refHeight - size.y) * 0.5f; position.y += (refHeight - textSize.y) * 0.5f;
break; break;
case VerticalAlign::Bottom: case VerticalAlign::Bottom:
position.y += refHeight - size.y; position.y += refHeight - textSize.y;
break; break;
case VerticalAlign::Top: case VerticalAlign::Top:
default: default:
@ -345,7 +323,8 @@ Vec2 Label::calculateDrawPosition() const {
* @param position * @param position
* @param color * @param color
*/ */
void Label::drawText(RenderBackend &renderer, const Vec2 &position, const Color &color) { void Label::drawText(RenderBackend &renderer, const Vec2 &position,
const Color &color) {
if (!font_ || text_.empty()) { if (!font_ || text_.empty()) {
return; return;
} }
@ -368,7 +347,7 @@ void Label::drawText(RenderBackend &renderer, const Vec2 &position, const Color
* @brief * @brief
* @return * @return
*/ */
Rect Label::getBoundingBox() const { Rect Label::boundingBox() const {
if (!font_ || text_.empty()) { if (!font_ || text_.empty()) {
return Rect(); return Rect();
} }

View File

@ -1,7 +1,7 @@
#include <ui/progress_bar.h>
#include <graphics/render_backend.h>
#include <core/string.h>
#include <cmath> #include <cmath>
#include <core/string.h>
#include <graphics/render_backend.h>
#include <ui/progress_bar.h>
namespace extra2d { namespace extra2d {
@ -17,9 +17,7 @@ ProgressBar::ProgressBar() {
* @brief * @brief
* @return * @return
*/ */
Ptr<ProgressBar> ProgressBar::create() { Ptr<ProgressBar> ProgressBar::create() { return makePtr<ProgressBar>(); }
return makePtr<ProgressBar>();
}
/** /**
* @brief * @brief
@ -67,7 +65,8 @@ void ProgressBar::setValue(float value) {
* @return 0.0-1.0 * @return 0.0-1.0
*/ */
float ProgressBar::getPercent() const { float ProgressBar::getPercent() const {
if (max_ <= min_) return 0.0f; if (max_ <= min_)
return 0.0f;
return (displayValue_ - min_) / (max_ - min_); return (displayValue_ - min_) / (max_ - min_);
} }
@ -75,25 +74,19 @@ float ProgressBar::getPercent() const {
* @brief * @brief
* @param dir * @param dir
*/ */
void ProgressBar::setDirection(Direction dir) { void ProgressBar::setDirection(Direction dir) { direction_ = dir; }
direction_ = dir;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void ProgressBar::setBackgroundColor(const Color &color) { void ProgressBar::setBackgroundColor(const Color &color) { bgColor_ = color; }
bgColor_ = color;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void ProgressBar::setFillColor(const Color &color) { void ProgressBar::setFillColor(const Color &color) { fillColor_ = color; }
fillColor_ = color;
}
/** /**
* @brief * @brief
@ -107,9 +100,7 @@ void ProgressBar::setGradientFillEnabled(bool enabled) {
* @brief * @brief
* @param color * @param color
*/ */
void ProgressBar::setFillColorEnd(const Color &color) { void ProgressBar::setFillColorEnd(const Color &color) { fillColorEnd_ = color; }
fillColorEnd_ = color;
}
/** /**
* @brief * @brief
@ -133,17 +124,13 @@ void ProgressBar::addColorSegment(float percentThreshold, const Color &color) {
/** /**
* @brief * @brief
*/ */
void ProgressBar::clearColorSegments() { void ProgressBar::clearColorSegments() { colorSegments_.clear(); }
colorSegments_.clear();
}
/** /**
* @brief * @brief
* @param radius * @param radius
*/ */
void ProgressBar::setCornerRadius(float radius) { void ProgressBar::setCornerRadius(float radius) { cornerRadius_ = radius; }
cornerRadius_ = radius;
}
/** /**
* @brief * @brief
@ -157,57 +144,43 @@ void ProgressBar::setRoundedCornersEnabled(bool enabled) {
* @brief * @brief
* @param enabled * @param enabled
*/ */
void ProgressBar::setBorderEnabled(bool enabled) { void ProgressBar::setBorderEnabled(bool enabled) { borderEnabled_ = enabled; }
borderEnabled_ = enabled;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void ProgressBar::setBorderColor(const Color &color) { void ProgressBar::setBorderColor(const Color &color) { borderColor_ = color; }
borderColor_ = color;
}
/** /**
* @brief * @brief
* @param width * @param width
*/ */
void ProgressBar::setBorderWidth(float width) { void ProgressBar::setBorderWidth(float width) { borderWidth_ = width; }
borderWidth_ = width;
}
/** /**
* @brief * @brief
* @param padding * @param padding
*/ */
void ProgressBar::setPadding(float padding) { void ProgressBar::setPadding(float padding) { padding_ = padding; }
padding_ = padding;
}
/** /**
* @brief * @brief
* @param enabled * @param enabled
*/ */
void ProgressBar::setTextEnabled(bool enabled) { void ProgressBar::setTextEnabled(bool enabled) { textEnabled_ = enabled; }
textEnabled_ = enabled;
}
/** /**
* @brief * @brief
* @param font * @param font
*/ */
void ProgressBar::setFont(Ptr<FontAtlas> font) { void ProgressBar::setFont(Ptr<FontAtlas> font) { font_ = font; }
font_ = font;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void ProgressBar::setTextColor(const Color &color) { void ProgressBar::setTextColor(const Color &color) { textColor_ = color; }
textColor_ = color;
}
/** /**
* @brief * @brief
@ -232,9 +205,7 @@ void ProgressBar::setAnimatedChangeEnabled(bool enabled) {
* @brief * @brief
* @param speed * @param speed
*/ */
void ProgressBar::setAnimationSpeed(float speed) { void ProgressBar::setAnimationSpeed(float speed) { animationSpeed_ = speed; }
animationSpeed_ = speed;
}
/** /**
* @brief * @brief
@ -248,9 +219,7 @@ void ProgressBar::setDelayedDisplayEnabled(bool enabled) {
* @brief * @brief
* @param seconds * @param seconds
*/ */
void ProgressBar::setDelayTime(float seconds) { void ProgressBar::setDelayTime(float seconds) { delayTime_ = seconds; }
delayTime_ = seconds;
}
/** /**
* @brief * @brief
@ -264,25 +233,19 @@ void ProgressBar::setDelayedFillColor(const Color &color) {
* @brief * @brief
* @param enabled * @param enabled
*/ */
void ProgressBar::setStripedEnabled(bool enabled) { void ProgressBar::setStripedEnabled(bool enabled) { stripedEnabled_ = enabled; }
stripedEnabled_ = enabled;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void ProgressBar::setStripeColor(const Color &color) { void ProgressBar::setStripeColor(const Color &color) { stripeColor_ = color; }
stripeColor_ = color;
}
/** /**
* @brief * @brief
* @param speed * @param speed
*/ */
void ProgressBar::setStripeSpeed(float speed) { void ProgressBar::setStripeSpeed(float speed) { stripeSpeed_ = speed; }
stripeSpeed_ = speed;
}
/** /**
* @brief * @brief
@ -330,8 +293,8 @@ std::string ProgressBar::formatText() const {
* @brief * @brief
* @return * @return
*/ */
Rect ProgressBar::getBoundingBox() const { Rect ProgressBar::boundingBox() const {
return Rect(pos().x, pos().y, getSize().width, getSize().height); return Rect(pos().x, pos().y, size().width, size().height);
} }
/** /**
@ -379,12 +342,12 @@ void ProgressBar::onUpdate(float deltaTime) {
*/ */
void ProgressBar::onDrawWidget(RenderBackend &renderer) { void ProgressBar::onDrawWidget(RenderBackend &renderer) {
Vec2 position = pos(); Vec2 position = pos();
Size size = getSize(); Size widgetSize = size();
float bgX = position.x + padding_; float bgX = position.x + padding_;
float bgY = position.y + padding_; float bgY = position.y + padding_;
float bgW = size.width - padding_ * 2; float bgW = widgetSize.width - padding_ * 2;
float bgH = size.height - padding_ * 2; float bgH = widgetSize.height - padding_ * 2;
Rect bgRect(bgX, bgY, bgW, bgH); Rect bgRect(bgX, bgY, bgW, bgH);
if (roundedCornersEnabled_) { if (roundedCornersEnabled_) {
@ -469,10 +432,8 @@ void ProgressBar::onDrawWidget(RenderBackend &renderer) {
std::string text = formatText(); std::string text = formatText();
Vec2 textSize = font_->measureText(text); Vec2 textSize = font_->measureText(text);
Vec2 textPos( Vec2 textPos(position.x + (widgetSize.width - textSize.x) * 0.5f,
position.x + (size.width - textSize.x) * 0.5f, position.y + (widgetSize.height - textSize.y) * 0.5f);
position.y + (size.height - textSize.y) * 0.5f
);
renderer.drawText(*font_, text, textPos, textColor_); renderer.drawText(*font_, text, textPos, textColor_);
} }
@ -485,7 +446,8 @@ void ProgressBar::onDrawWidget(RenderBackend &renderer) {
* @param color * @param color
* @param radius * @param radius
*/ */
void ProgressBar::drawRoundedRect(RenderBackend &renderer, const Rect &rect, const Color &color, float radius) { void ProgressBar::drawRoundedRect(RenderBackend &renderer, const Rect &rect,
const Color &color, float radius) {
renderer.drawRect(rect, color, borderWidth_); renderer.drawRect(rect, color, borderWidth_);
} }
@ -496,7 +458,8 @@ void ProgressBar::drawRoundedRect(RenderBackend &renderer, const Rect &rect, con
* @param color * @param color
* @param radius * @param radius
*/ */
void ProgressBar::fillRoundedRect(RenderBackend &renderer, const Rect &rect, const Color &color, float radius) { void ProgressBar::fillRoundedRect(RenderBackend &renderer, const Rect &rect,
const Color &color, float radius) {
renderer.fillRect(rect, color); renderer.fillRect(rect, color);
} }
@ -511,14 +474,17 @@ void ProgressBar::drawStripes(RenderBackend &renderer, const Rect &rect) {
float rectRight = rect.origin.x + rect.size.width; float rectRight = rect.origin.x + rect.size.width;
float rectBottom = rect.origin.y + rect.size.height; float rectBottom = rect.origin.y + rect.size.height;
for (float x = rect.origin.x - spacing + stripeOffset_; x < rectRight; x += spacing) { for (float x = rect.origin.x - spacing + stripeOffset_; x < rectRight;
x += spacing) {
float x1 = x; float x1 = x;
float y1 = rect.origin.y; float y1 = rect.origin.y;
float x2 = x + stripeWidth; float x2 = x + stripeWidth;
float y2 = rectBottom; float y2 = rectBottom;
if (x1 < rect.origin.x) x1 = rect.origin.x; if (x1 < rect.origin.x)
if (x2 > rectRight) x2 = rectRight; x1 = rect.origin.x;
if (x2 > rectRight)
x2 = rectRight;
if (x2 > x1) { if (x2 > x1) {
for (int i = 0; i < static_cast<int>(rect.size.height); i += 4) { for (int i = 0; i < static_cast<int>(rect.size.height); i += 4) {

View File

@ -1,6 +1,6 @@
#include <ui/radio_button.h>
#include <graphics/render_backend.h>
#include <core/string.h> #include <core/string.h>
#include <graphics/render_backend.h>
#include <ui/radio_button.h>
namespace extra2d { namespace extra2d {
@ -16,9 +16,7 @@ RadioButton::RadioButton() {
* @brief * @brief
* @return * @return
*/ */
Ptr<RadioButton> RadioButton::create() { Ptr<RadioButton> RadioButton::create() { return makePtr<RadioButton>(); }
return makePtr<RadioButton>();
}
/** /**
* @brief * @brief
@ -48,41 +46,31 @@ void RadioButton::setSelected(bool selected) {
* @brief * @brief
* @param label * @param label
*/ */
void RadioButton::setLabel(const std::string &label) { void RadioButton::setLabel(const std::string &label) { label_ = label; }
label_ = label;
}
/** /**
* @brief * @brief
* @param font * @param font
*/ */
void RadioButton::setFont(Ptr<FontAtlas> font) { void RadioButton::setFont(Ptr<FontAtlas> font) { font_ = font; }
font_ = font;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void RadioButton::setTextColor(const Color &color) { void RadioButton::setTextColor(const Color &color) { textColor_ = color; }
textColor_ = color;
}
/** /**
* @brief * @brief
* @param size * @param size
*/ */
void RadioButton::setCircleSize(float size) { void RadioButton::setCircleSize(float size) { circleSize_ = size; }
circleSize_ = size;
}
/** /**
* @brief * @brief
* @param spacing * @param spacing
*/ */
void RadioButton::setSpacing(float spacing) { void RadioButton::setSpacing(float spacing) { spacing_ = spacing; }
spacing_ = spacing;
}
/** /**
* @brief * @brief
@ -104,17 +92,13 @@ void RadioButton::setUnselectedColor(const Color &color) {
* @brief * @brief
* @param color * @param color
*/ */
void RadioButton::setDotColor(const Color &color) { void RadioButton::setDotColor(const Color &color) { dotColor_ = color; }
dotColor_ = color;
}
/** /**
* @brief ID * @brief ID
* @param groupId ID * @param groupId ID
*/ */
void RadioButton::setGroupId(int groupId) { void RadioButton::setGroupId(int groupId) { groupId_ = groupId; }
groupId_ = groupId;
}
/** /**
* @brief * @brief
@ -128,7 +112,7 @@ void RadioButton::setOnStateChange(Function<void(bool)> callback) {
* @brief * @brief
* @return * @return
*/ */
Rect RadioButton::getBoundingBox() const { Rect RadioButton::boundingBox() const {
Vec2 position = pos(); Vec2 position = pos();
float width = circleSize_; float width = circleSize_;
@ -147,12 +131,13 @@ Rect RadioButton::getBoundingBox() const {
void RadioButton::onDrawWidget(RenderBackend &renderer) { void RadioButton::onDrawWidget(RenderBackend &renderer) {
Vec2 position = pos(); Vec2 position = pos();
float centerX = position.x + circleSize_ * 0.5f; float centerX = position.x + circleSize_ * 0.5f;
float centerY = position.y + getSize().height * 0.5f; float centerY = position.y + size().height * 0.5f;
float radius = circleSize_ * 0.5f; float radius = circleSize_ * 0.5f;
Color circleColor = selected_ ? selectedColor_ : unselectedColor_; Color circleColor = selected_ ? selectedColor_ : unselectedColor_;
renderer.drawCircle(Vec2(centerX, centerY), radius, circleColor, true); renderer.drawCircle(Vec2(centerX, centerY), radius, circleColor, true);
renderer.drawCircle(Vec2(centerX, centerY), radius, Colors::White, false, 1.0f); renderer.drawCircle(Vec2(centerX, centerY), radius, Colors::White, false,
1.0f);
if (selected_) { if (selected_) {
float dotRadius = radius * 0.4f; float dotRadius = radius * 0.4f;
@ -188,7 +173,7 @@ bool RadioButton::onMouseRelease(const MouseEvent &event) {
pressed_ = false; pressed_ = false;
Vec2 position = pos(); Vec2 position = pos();
float centerX = position.x + circleSize_ * 0.5f; float centerX = position.x + circleSize_ * 0.5f;
float centerY = position.y + getSize().height * 0.5f; float centerY = position.y + size().height * 0.5f;
float radius = circleSize_ * 0.5f; float radius = circleSize_ * 0.5f;
float dx = event.x - centerX; float dx = event.x - centerX;
@ -210,7 +195,8 @@ bool RadioButton::onMouseRelease(const MouseEvent &event) {
* @param button * @param button
*/ */
void RadioButtonGroup::addButton(RadioButton *button) { void RadioButtonGroup::addButton(RadioButton *button) {
if (button && std::find(buttons_.begin(), buttons_.end(), button) == buttons_.end()) { if (button &&
std::find(buttons_.begin(), buttons_.end(), button) == buttons_.end()) {
buttons_.push_back(button); buttons_.push_back(button);
button->setOnStateChange([this, button](bool selected) { button->setOnStateChange([this, button](bool selected) {
if (selected) { if (selected) {
@ -243,7 +229,8 @@ void RadioButtonGroup::removeButton(RadioButton *button) {
* @param button * @param button
*/ */
void RadioButtonGroup::selectButton(RadioButton *button) { void RadioButtonGroup::selectButton(RadioButton *button) {
if (selectedButton_ == button) return; if (selectedButton_ == button)
return;
if (selectedButton_) { if (selectedButton_) {
selectedButton_->setSelected(false); selectedButton_->setSelected(false);
@ -263,7 +250,8 @@ void RadioButtonGroup::selectButton(RadioButton *button) {
* @brief * @brief
* @param callback * @param callback
*/ */
void RadioButtonGroup::setOnSelectionChange(Function<void(RadioButton*)> callback) { void RadioButtonGroup::setOnSelectionChange(
Function<void(RadioButton *)> callback) {
onSelectionChange_ = callback; onSelectionChange_ = callback;
} }

View File

@ -1,7 +1,7 @@
#include <ui/slider.h>
#include <graphics/render_backend.h>
#include <core/string.h>
#include <cmath> #include <cmath>
#include <core/string.h>
#include <graphics/render_backend.h>
#include <ui/slider.h>
namespace extra2d { namespace extra2d {
@ -17,9 +17,7 @@ Slider::Slider() {
* @brief * @brief
* @return * @return
*/ */
Ptr<Slider> Slider::create() { Ptr<Slider> Slider::create() { return makePtr<Slider>(); }
return makePtr<Slider>();
}
/** /**
* @brief * @brief
@ -79,49 +77,37 @@ void Slider::setStep(float step) {
* @brief * @brief
* @param vertical * @param vertical
*/ */
void Slider::setVertical(bool vertical) { void Slider::setVertical(bool vertical) { vertical_ = vertical; }
vertical_ = vertical;
}
/** /**
* @brief * @brief
* @param size * @param size
*/ */
void Slider::setTrackSize(float size) { void Slider::setTrackSize(float size) { trackSize_ = size; }
trackSize_ = size;
}
/** /**
* @brief * @brief
* @param size * @param size
*/ */
void Slider::setThumbSize(float size) { void Slider::setThumbSize(float size) { thumbSize_ = size; }
thumbSize_ = size;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void Slider::setTrackColor(const Color &color) { void Slider::setTrackColor(const Color &color) { trackColor_ = color; }
trackColor_ = color;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void Slider::setFillColor(const Color &color) { void Slider::setFillColor(const Color &color) { fillColor_ = color; }
fillColor_ = color;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void Slider::setThumbColor(const Color &color) { void Slider::setThumbColor(const Color &color) { thumbColor_ = color; }
thumbColor_ = color;
}
/** /**
* @brief * @brief
@ -143,49 +129,37 @@ void Slider::setThumbPressedColor(const Color &color) {
* @brief * @brief
* @param show * @param show
*/ */
void Slider::setShowThumb(bool show) { void Slider::setShowThumb(bool show) { showThumb_ = show; }
showThumb_ = show;
}
/** /**
* @brief * @brief
* @param show * @param show
*/ */
void Slider::setShowFill(bool show) { void Slider::setShowFill(bool show) { showFill_ = show; }
showFill_ = show;
}
/** /**
* @brief * @brief
* @param enabled * @param enabled
*/ */
void Slider::setTextEnabled(bool enabled) { void Slider::setTextEnabled(bool enabled) { textEnabled_ = enabled; }
textEnabled_ = enabled;
}
/** /**
* @brief * @brief
* @param font * @param font
*/ */
void Slider::setFont(Ptr<FontAtlas> font) { void Slider::setFont(Ptr<FontAtlas> font) { font_ = font; }
font_ = font;
}
/** /**
* @brief * @brief
* @param color * @param color
*/ */
void Slider::setTextColor(const Color &color) { void Slider::setTextColor(const Color &color) { textColor_ = color; }
textColor_ = color;
}
/** /**
* @brief * @brief
* @param format * @param format
*/ */
void Slider::setTextFormat(const std::string &format) { void Slider::setTextFormat(const std::string &format) { textFormat_ = format; }
textFormat_ = format;
}
/** /**
* @brief * @brief
@ -207,16 +181,14 @@ void Slider::setOnDragStart(Function<void()> callback) {
* @brief * @brief
* @param callback * @param callback
*/ */
void Slider::setOnDragEnd(Function<void()> callback) { void Slider::setOnDragEnd(Function<void()> callback) { onDragEnd_ = callback; }
onDragEnd_ = callback;
}
/** /**
* @brief * @brief
* @return * @return
*/ */
Rect Slider::getBoundingBox() const { Rect Slider::boundingBox() const {
return Rect(pos().x, pos().y, getSize().width, getSize().height); return Rect(pos().x, pos().y, size().width, size().height);
} }
/** /**
@ -226,14 +198,14 @@ Rect Slider::getBoundingBox() const {
*/ */
float Slider::valueToPosition(float value) const { float Slider::valueToPosition(float value) const {
Vec2 position = pos(); Vec2 position = pos();
Size size = getSize(); Size sz = size();
float percent = (value - min_) / (max_ - min_); float percent = (value - min_) / (max_ - min_);
if (vertical_) { if (vertical_) {
return position.y + size.height - percent * size.height; return position.y + sz.height - percent * sz.height;
} else { } else {
return position.x + percent * size.width; return position.x + percent * sz.width;
} }
} }
@ -244,13 +216,13 @@ float Slider::valueToPosition(float value) const {
*/ */
float Slider::positionToValue(float position) const { float Slider::positionToValue(float position) const {
Vec2 widgetPos = pos(); Vec2 widgetPos = pos();
Size size = getSize(); Size widgetSize = size();
float percent; float percent;
if (vertical_) { if (vertical_) {
percent = (widgetPos.y + size.height - position) / size.height; percent = (widgetPos.y + widgetSize.height - position) / widgetSize.height;
} else { } else {
percent = (position - widgetPos.x) / size.width; percent = (position - widgetPos.x) / widgetSize.width;
} }
percent = std::clamp(percent, 0.0f, 1.0f); percent = std::clamp(percent, 0.0f, 1.0f);
@ -262,25 +234,18 @@ float Slider::positionToValue(float position) const {
* @return * @return
*/ */
Rect Slider::getThumbRect() const { Rect Slider::getThumbRect() const {
Vec2 position = pos(); Vec2 widgetPos = pos();
Size size = getSize(); Size widgetSize = size();
float thumbPos = valueToPosition(value_); float thumbPos = valueToPosition(value_);
if (vertical_) { if (vertical_) {
return Rect( return Rect(widgetPos.x + (widgetSize.width - thumbSize_) * 0.5f,
position.x + (size.width - thumbSize_) * 0.5f, thumbPos - thumbSize_ * 0.5f, thumbSize_, thumbSize_);
thumbPos - thumbSize_ * 0.5f,
thumbSize_,
thumbSize_
);
} else { } else {
return Rect( return Rect(thumbPos - thumbSize_ * 0.5f,
thumbPos - thumbSize_ * 0.5f, widgetPos.y + (widgetSize.height - thumbSize_) * 0.5f,
position.y + (size.height - thumbSize_) * 0.5f, thumbSize_, thumbSize_);
thumbSize_,
thumbSize_
);
} }
} }
@ -289,23 +254,16 @@ Rect Slider::getThumbRect() const {
* @return * @return
*/ */
Rect Slider::getTrackRect() const { Rect Slider::getTrackRect() const {
Vec2 position = pos(); Vec2 widgetPos = pos();
Size size = getSize(); Size widgetSize = size();
if (vertical_) { if (vertical_) {
return Rect( return Rect(widgetPos.x + (widgetSize.width - trackSize_) * 0.5f,
position.x + (size.width - trackSize_) * 0.5f, widgetPos.y, trackSize_, widgetSize.height);
position.y,
trackSize_,
size.height
);
} else { } else {
return Rect( return Rect(widgetPos.x,
position.x, widgetPos.y + (widgetSize.height - trackSize_) * 0.5f,
position.y + (size.height - trackSize_) * 0.5f, widgetSize.width, trackSize_);
size.width,
trackSize_
);
} }
} }
@ -326,7 +284,8 @@ std::string Slider::formatText() const {
size_t endPos = result.find("}", pos); size_t endPos = result.find("}", pos);
if (endPos != std::string::npos) { if (endPos != std::string::npos) {
std::string format = result.substr(pos + 7, endPos - pos - 8); std::string format = result.substr(pos + 7, endPos - pos - 8);
result.replace(pos, endPos - pos + 1, std::to_string(static_cast<int>(value_))); result.replace(pos, endPos - pos + 1,
std::to_string(static_cast<int>(value_)));
} }
} }
@ -387,13 +346,11 @@ void Slider::onDrawWidget(RenderBackend &renderer) {
if (textEnabled_ && font_) { if (textEnabled_ && font_) {
std::string text = formatText(); std::string text = formatText();
Vec2 textSize = font_->measureText(text); Vec2 textSize = font_->measureText(text);
Vec2 position = pos(); Vec2 widgetPos = pos();
Size size = getSize(); Size widgetSize = size();
Vec2 textPos( Vec2 textPos(widgetPos.x + widgetSize.width + 10.0f,
position.x + size.width + 10.0f, widgetPos.y + (widgetSize.height - textSize.y) * 0.5f);
position.y + (size.height - textSize.y) * 0.5f
);
renderer.drawText(*font_, text, textPos, textColor_); renderer.drawText(*font_, text, textPos, textColor_);
} }
@ -468,15 +425,11 @@ bool Slider::onMouseMove(const MouseEvent &event) {
/** /**
* @brief * @brief
*/ */
void Slider::onMouseEnter() { void Slider::onMouseEnter() { hovered_ = true; }
hovered_ = true;
}
/** /**
* @brief * @brief
*/ */
void Slider::onMouseLeave() { void Slider::onMouseLeave() { hovered_ = false; }
hovered_ = false;
}
} // namespace extra2d } // namespace extra2d

View File

@ -1,10 +1,9 @@
#include <core/string.h>
#include <cstdarg> #include <cstdarg>
#include <cstdio> #include <cstdio>
#include <core/string.h>
#include <graphics/render_backend.h> #include <graphics/render_backend.h>
#include <ui/text.h> #include <ui/text.h>
namespace extra2d { namespace extra2d {
/** /**
@ -114,7 +113,7 @@ void Text::updateCache() const {
Vec2 Text::calculateDrawPosition() const { Vec2 Text::calculateDrawPosition() const {
Vec2 position = pos(); Vec2 position = pos();
Vec2 textSize = getTextSize(); Vec2 textSize = getTextSize();
Size widgetSize = getSize(); Size widgetSize = size();
Vec2 anchorPt = anchor(); Vec2 anchorPt = anchor();
float refWidth = widgetSize.empty() ? textSize.x : widgetSize.width; float refWidth = widgetSize.empty() ? textSize.x : widgetSize.width;
@ -216,7 +215,7 @@ Ptr<Text> Text::createFormat(Ptr<FontAtlas> font, const char *fmt, ...) {
* @brief * @brief
* @return * @return
*/ */
Rect Text::getBoundingBox() const { Rect Text::boundingBox() const {
if (!font_ || text_.empty()) { if (!font_ || text_.empty()) {
return Rect(); return Rect();
} }

View File

@ -3,9 +3,7 @@
namespace extra2d { namespace extra2d {
Widget::Widget() { Widget::Widget() { setSpatialIndexed(false); }
setSpatialIndexed(false);
}
void Widget::setSize(const Size &size) { void Widget::setSize(const Size &size) {
size_ = size; size_ = size;
@ -16,7 +14,7 @@ void Widget::setSize(float width, float height) {
setSize(Size(width, height)); setSize(Size(width, height));
} }
Rect Widget::getBoundingBox() const { Rect Widget::boundingBox() const {
if (size_.empty()) { if (size_.empty()) {
return Rect(); return Rect();
} }
@ -40,8 +38,6 @@ Rect Widget::getBoundingBox() const {
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// 重写 onDraw // 重写 onDraw
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
void Widget::onDraw(RenderBackend &renderer) { void Widget::onDraw(RenderBackend &renderer) { onDrawWidget(renderer); }
onDrawWidget(renderer);
}
} // namespace extra2d } // namespace extra2d