-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathButton.cpp
More file actions
110 lines (94 loc) · 1.96 KB
/
Button.cpp
File metadata and controls
110 lines (94 loc) · 1.96 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include "Button.h"
#include "Font.h"
Button::Button(const std::string& name, Font* font, std::function<void()> onClick, const Vector2& pos, const Vector2& dim) : mName(name)
, mFont(font)
, mNameTexture(nullptr)
, mPosition(pos)
, mDimension(dim)
, mHighlighted(false)
, mOnClick(onClick)
, mNameTexHeight(0)
, mNameTexWidth(0)
, mFontSize(12)
{
if (name != "") SetName(name);
SDL_Log("Button named: [%s] has been created.", name.c_str());
if (!onClick) SDL_Log("null function");
}
Button::~Button()
{
if (mNameTexture) SDL_DestroyTexture(mNameTexture);
}
void Button::SetName(const std::string& name)
{
if (!mFont)
{
SDL_Log("Font is null");
return;
}
{
if (name == "")
{
return;
}
mName = name;
if (mNameTexture)
{
SDL_DestroyTexture(mNameTexture);
mNameTexture = nullptr;
}
mNameTexture = mFont->RenderText(mName, Color::White, mFontSize);
SDL_QueryTexture(mNameTexture, NULL, NULL, &mNameTexWidth, &mNameTexHeight);
}
}
bool Button::ContainsPoint(const Vector2& pt) const
{
bool no = pt.x < (mPosition.x - mDimension.x / 2.0f) ||
pt.x >(mPosition.x + mDimension.x / 2.0f) ||
pt.y < (mPosition.y - mDimension.y / 2.0f) ||
pt.y >(mPosition.y + mDimension.y / 2.0f);
return !no;
}
void Button::OnClick()
{
if (mOnClick)
{
mOnClick();
}
}
void Button::Draw(SDL_Texture* tex, SDL_Renderer* renderer)
{
Vector2 dim = GetDimension();
Vector2 pos = GetPosition();
SDL_Rect r;
r.w = (int)dim.x;
r.h = (int)dim.y;
r.x = (int)pos.x - dim.x / 2;
r.y = (int)pos.y - dim.y / 2;
SDL_RenderCopyEx(renderer,
tex,
nullptr,
&r,
0.0,
nullptr,
SDL_FLIP_NONE);
int x = 0;
int y = 0;
if (!mNameTexture && mName != "")
{
SetName(mName);
}
if (mName == "") return;
SDL_Rect dstRect;
dstRect.w = mNameTexWidth;
dstRect.h = mNameTexHeight;
dstRect.x = r.x + (r.w - dstRect.w) / 2;
dstRect.y = r.y + (r.h - dstRect.h) / 2;
SDL_RenderCopyEx(renderer,
mNameTexture,
nullptr,
&dstRect,
0.0,
nullptr,
SDL_FLIP_NONE);
}