1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
#include "../../include/gui/Button.hpp"
#include "../../include/Theme.hpp"
#include "../../include/Config.hpp"
#include <mglpp/system/FloatRect.hpp>
#include <mglpp/window/Window.hpp>
#include <mglpp/window/Event.hpp>
#include <cmath>
namespace QuickMedia {
static const float PADDING_Y = 5.0f;
Button::Button(const std::string &label, mgl::Font *font, float width, mgl::Shader *rounded_rectangle_shader, float scale) :
label(label, *font),
background(mgl::vec2f(1.0f, 1.0f), 10.0f * get_config().scale, get_theme().shade_color, rounded_rectangle_shader),
scale(scale)
{
background.set_size(mgl::vec2f(std::floor(width * scale), get_height()));
set_position(mgl::vec2f(0.0f, 0.0f));
}
ButtonEvent Button::on_event(mgl::Event &event) {
ButtonEvent performed_event = BUTTON_EVENT_NONE;
if(event.type == mgl::Event::MouseMoved) {
if(mgl::FloatRect(background.get_position(), background.get_size()).contains(mgl::vec2f(event.mouse_move.x, event.mouse_move.y))) {
const int inc = 20;
background.set_color(mgl::Color(
std::min(255, (int)background_color.r + inc),
std::min(255, (int)background_color.g + inc),
std::min(255, (int)background_color.b + inc)));
} else {
background.set_color(background_color);
}
} else if(event.type == mgl::Event::MouseButtonPressed) {
if(event.mouse_button.button == mgl::Mouse::Left && mgl::FloatRect(background.get_position(), background.get_size()).contains(mgl::vec2f(event.mouse_button.x, event.mouse_button.y))) {
clicked_inside = true;
} else {
clicked_inside = false;
}
} else if(event.type == mgl::Event::MouseButtonReleased) {
if(clicked_inside && event.mouse_button.button == mgl::Mouse::Left && mgl::FloatRect(background.get_position(), background.get_size()).contains(mgl::vec2f(event.mouse_button.x, event.mouse_button.y))) {
performed_event = BUTTON_EVENT_CLICKED;
}
clicked_inside = false;
}
return performed_event;
}
void Button::draw(mgl::Window &target) {
background.draw(target);
target.draw(label);
}
void Button::set_background_color(mgl::Color color) {
background_color = color;
background.set_color(background_color);
}
void Button::set_position(mgl::vec2f pos) {
background.set_position(pos);
const auto label_bounds = label.get_bounds();
mgl::vec2f label_pos(pos + background.get_size() * 0.5f - label_bounds.size * 0.5f - mgl::vec2f(0.0f, 5.0f * scale));
label_pos.x = std::floor(label_pos.x);
label_pos.y = std::floor(label_pos.y);
label.set_position(label_pos);
}
mgl::vec2f Button::get_position() const {
return background.get_position();
}
float Button::get_width() const {
return background.get_size().x;
}
float Button::get_height() {
return std::floor((PADDING_Y * 2.0f) * scale + label.get_bounds().size.y);
}
}
|