TinyMaterialDesign
Loading...
Searching...
No Matches
Badge.h
Go to the documentation of this file.
1#pragma once
2#include <string>
3
4#include "TinyGPU/Color/RGB565.h"
5#include "TinyGPU/Color/RGB666.h"
6#include "TinyGPU/Color/RGB888.h"
7#include "TinyMaterialDesign/Core/Widget.h"
8
9namespace tinymd {
10
11/**
12 * @brief Small status marker, typically overlaid on an icon's corner.
13 *
14 * Non-interactive. Either a plain dot (no text set) or a small filled pill
15 * holding a short count/label (e.g. "3", "9+"). Position its own `bounds`
16 * over whatever it's badging - e.g. the top-right corner of an IconButton's
17 * bounds - the caller is responsible for that placement, same as any other
18 * widget.
19 */
20template <typename RGB_T = TINYMD_DEFAULT_RGB_T>
21class Badge : public Widget<RGB_T> {
22 public:
23 Badge() = default;
24 explicit Badge(Bounds bounds, const char* text = nullptr) {
25 this->bounds = bounds;
26 if (text != nullptr) text_ = text;
27 }
28
29 void setText(const char* text) { text_ = text != nullptr ? text : ""; }
30 const std::string& text() const { return text_; }
31
32 void draw(tinygpu::ISurface<RGB_T>& target) override {
33 RGB_T background = this->theme().colors.error;
34 RGB_T foreground = this->theme().colors.onError;
35 if (!this->enabled) {
36 background = blend(background, this->theme().colors.surface, 0.5f);
37 foreground = blend(foreground, this->theme().colors.surface, 0.5f);
38 }
39
40 if (text_.empty()) {
41 const int32_t diameter = this->bounds.w < this->bounds.h ? this->bounds.w : this->bounds.h;
42 target.fillCircle(toPx(this->bounds.centerX()), toPx(this->bounds.centerY()),
43 toPx(diameter / 2), background);
44 return;
45 }
46
47 const size_t radius = toPx(this->bounds.h / 2);
48 target.fillRoundRect(toPx(this->bounds.x), toPx(this->bounds.y), toPx(this->bounds.w),
49 toPx(this->bounds.h), radius, background);
50
51 tinygpu::IFont<RGB_T>& font = *this->theme().typography.label;
52 const size_t textWidth = font.measureTextWidth(text_.c_str());
53 const int32_t textX = this->bounds.centerX() - static_cast<int32_t>(textWidth) / 2;
54 const int32_t textY = this->bounds.centerY() - static_cast<int32_t>(font.getHeight(1)) / 2;
55 font.drawText(target, static_cast<int16_t>(textX), static_cast<int16_t>(textY), text_.c_str(),
56 foreground, background, false);
57 }
58
59 private:
60 std::string text_;
61};
62
66
67} // namespace tinymd
Small status marker, typically overlaid on an icon's corner.
Definition: Badge.h:21
void setText(const char *text)
Definition: Badge.h:29
Badge(Bounds bounds, const char *text=nullptr)
Definition: Badge.h:24
void draw(tinygpu::ISurface< RGB_T > &target) override
Definition: Badge.h:32
const std::string & text() const
Definition: Badge.h:30
Badge()=default
Base class every TinyMaterialDesign widget derives from.
Definition: Widget.h:58
Definition: AnchorLayout.h:4
Axis-aligned pixel rectangle used for widget bounds and hit-testing.
Definition: Bounds.h:21