'How to center align text horizontally?
I am creating a text in ImGui. It automatically aligns right, how do I make just that one text align in the center?
ImGui::Text("Example Text");
I don't believe there is a function to do this. I know you can do it for a box or widget, but how would I for a simple text?
Solution 1:[1]
void TextCentered(std::string text) {
auto windowWidth = ImGui::GetWindowSize().x;
auto textWidth = ImGui::CalcTextSize(text.c_str()).x;
ImGui::SetCursorPosX((windowWidth - textWidth) * 0.5f);
ImGui::Text(text.c_str());
}
Solution 2:[2]
Just want to add a solution for multi-line text to save 5 minutes for someone.
void TextCentered(std::string text) {
float win_width = ImGui::GetWindowSize().x;
float text_width = ImGui::CalcTextSize(text.c_str()).x;
// calculate the indentation that centers the text on one line, relative
// to window left, regardless of the `ImGuiStyleVar_WindowPadding` value
float text_indentation = (win_width - text_width) * 0.5f;
// if text is too long to be drawn on one line, `text_indentation` can
// become too small or even negative, so we check a minimum indentation
float min_indentation = 20.0f;
if (text_indentation <= min_indentation) {
text_indentation = min_indentation;
}
ImGui::SameLine(text_indentation);
ImGui::PushTextWrapPos(win_width - text_indentation);
ImGui::TextWrapped(text.c_str());
ImGui::PopTextWrapPos();
}
Solution 3:[3]
This comment on a similar GitHub issue could help, haven't tried it myself though:
void TextCenter(std::string text) {
float font_size = ImGui::GetFontSize() * text.size() / 2;
ImGui::SameLine(
ImGui::GetWindowSize().x / 2 -
font_size + (font_size / 2)
);
ImGui::Text(text.c_str());
}
Solution 4:[4]
Well more performant way without std::string
void TextCenter(const char* text, ...) {
va_list vaList = nullptr;
va_start(vaList, &text, );
float font_size = ImGui::GetFontSize() * strlen(text) / 2;
ImGui::SameLine(
ImGui::GetWindowSize().x / 2 -
font_size + (font_size / 2)
);
ImGui::TextV(text, vaList);
va_end(vaList);
}
Solution 5:[5]
In short:
void DrawTextCentered(const char* text)
{
ImGui::SetCursorPosX( (ImGui::GetWindowWidth() - ImGui::CalcTextSize(text).x) / 2.f);
ImGui::Text(text);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | neo-mashiro |
Solution 3 | schnaader |
Solution 4 | Hendrik A. |
Solution 5 | NullifiedVlad |