7

我正在 ImGui 中创建文本。它会自动对齐,如何使一个文本在中心对齐?

ImGui::Text("Example Text");

我不相信有这样做的功能。我知道你可以为一个盒子或小部件做到这一点,但我将如何处理一个简单的文本?

4

4 回答 4

6
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());
}
于 2021-06-06T05:17:06.177 回答
5

只想为多行文本添加一个解决方案,为某人节省 5 分钟。

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();
}
于 2021-11-22T22:28:16.543 回答
2

对类似 GitHub 问题的评论可能会有所帮助,但我自己没有尝试过:

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());
}
于 2021-01-13T16:25:03.913 回答
0

没有 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);
}
于 2021-11-18T16:52:36.347 回答