yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
centered_icon_button.cc
Go to the documentation of this file.
1#define IMGUI_DEFINE_MATH_OPERATORS
3
4#include <algorithm>
5
7#include "imgui/imgui.h"
8#include "imgui/imgui_internal.h"
9
10namespace yaze::gui {
11
12// Material icons are merged with a text-baseline offset. Center their visible
13// glyph bounds, not the text line box, while retaining ordinary button input,
14// navigation, IDs, and disabled styling. This is for one-glyph controls only.
15bool CenteredIconButton(const char* label, float button_size) {
16 const bool pressed = [&] {
17 StyleColorGuard transparent_text(ImGuiCol_Text, ImVec4(0, 0, 0, 0));
18 return ImGui::Button(label, ImVec2(button_size, button_size));
19 }();
20 if (!ImGui::IsItemVisible())
21 return pressed;
22
23 unsigned int codepoint = 0;
24 ImTextCharFromUtf8(&codepoint, label, nullptr);
25 auto* baked = ImGui::GetFontBaked();
26 const auto* glyph = baked->FindGlyph(static_cast<ImWchar>(codepoint));
27 if (!glyph || !glyph->Visible)
28 return pressed;
29
30 const float font_scale = ImGui::GetFontSize() / baked->Size;
31 const float width = (glyph->X1 - glyph->X0) * font_scale;
32 const float height = (glyph->Y1 - glyph->Y0) * font_scale;
33 if (width <= 0 || height <= 0)
34 return pressed;
35 const ImVec2 min = ImGui::GetItemRectMin();
36 const ImVec2 max = ImGui::GetItemRectMax();
37 // Keep the existing compact frame size; fit oversized glyphs inside it.
38 const float inset = ImGui::GetFontSize() / 8.0f;
39 const float available = std::max(1.0f, button_size - 2 * inset);
40 const float fit = std::min({1.0f, available / width, available / height});
41 const ImVec2 glyph_size(width * fit, height * fit);
42 const ImVec2 glyph_min((min.x + max.x - glyph_size.x) * 0.5f,
43 (min.y + max.y - glyph_size.y) * 0.5f);
44 ImGui::GetWindowDrawList()->AddImage(
45 ImGui::GetFont()->OwnerAtlas->TexRef, glyph_min,
46 ImVec2(glyph_min.x + glyph_size.x, glyph_min.y + glyph_size.y),
47 ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1),
48 ImGui::GetColorU32(ImGuiCol_Text));
49 return pressed;
50}
51
52} // namespace yaze::gui
RAII guard for ImGui style colors.
Definition style_guard.h:29
Graphical User Interface (GUI) components for the application.
bool CenteredIconButton(const char *label, float button_size)