Root/src/iconbutton.cpp

Source at commit 00d3c3b57008bddf8770c51271db9d766acaf854 created 7 years 5 months ago.
By Maarten ter Huurne, Gave Layer class a protected constructor
1#include "iconbutton.h"
2
3#include "font.h"
4#include "gmenu2x.h"
5#include "surface.h"
6
7using namespace std;
8
9
10IconButton::IconButton(
11        GMenu2X& gmenu2x, const string &icon, const string &label,
12        Action action)
13    : gmenu2x(gmenu2x)
14    , icon(icon)
15    , label(label)
16    , action(action)
17    , rect({ 0, 0, 0, 0 })
18{
19    iconSurface = gmenu2x.sc[icon];
20    recalcRects();
21}
22
23void IconButton::setPosition(int x, int y) {
24    if (rect.x != x || rect.y != y) {
25        rect.x = x;
26        rect.y = y;
27        recalcRects();
28    }
29}
30
31void IconButton::recalcRects() {
32    Uint16 h = 0, w = 0;
33    if (iconSurface) {
34        w += iconSurface->width();
35        h += iconSurface->height();
36    }
37    iconRect = { rect.x, rect.y, w, h };
38
39    if (!label.empty()) {
40        Uint16 margin = iconSurface ? 2 : 0;
41        labelRect = {
42            static_cast<Sint16>(iconRect.x + iconRect.w + margin),
43            static_cast<Sint16>(rect.y + h / 2),
44            static_cast<Uint16>(gmenu2x.font->getTextWidth(label)),
45            static_cast<Uint16>(gmenu2x.font->getLineSpacing())
46        };
47        w += margin + labelRect.w;
48    }
49
50    rect.w = w;
51    rect.h = h;
52}
53
54void IconButton::paint(Surface& s) {
55    if (iconSurface) {
56        iconSurface->blit(s, iconRect);
57    }
58    if (!label.empty()) {
59        gmenu2x.font->write(s, label, labelRect.x, labelRect.y,
60                Font::HAlignLeft, Font::VAlignMiddle);
61    }
62}
63

Archive Download this file



interactive