c++ - SFML 绘图居中文本

标签 c++ sfml

我试图在 SFML 中将一些文本居中。正如您在下图中看到的那样,它并没有真正起作用。 enter image description here

也许我的数学有问题?

void TextRenderer::renderCentered(sf::RenderWindow& window, std::string string, sf::Vector2f     position, int size, sf::Color color) {
    sf::Text text;

    text.setFont(TextRenderer::kavoon);
    text.setString(string);

    float width = text.getLocalBounds().width;

    text.setPosition(position.x - width / 2, position.y);

    text.setCharacterSize(size);
    text.setColor(color);

    window.draw(text);
}

在渲染方法中:

TextRenderer::renderCentered(*window, pickuptext.str(), sf::Vector2f(player->sprite.getPosition().x, player->sprite.getPosition().y - 48), 28, sf::Color(255, 145, 61));
TextRenderer::renderCentered(*window, pickuptextdesc.str(), sf::Vector2f(player->sprite.getPosition().x, player->sprite.getPosition().y - 16), 18, sf::Color(255, 145, 61));

最佳答案

在边界框内水平居中文本的公式是:

text_start = bounding_box_width / 2 - text_width / 2;

看起来您可能没有提供边界框水平中心点。

关于c++ - SFML 绘图居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27806077/

相关文章:

Objective-C++ 中的 C++ 堆栈

c++ - 链接 SFML 时出错。 LNK2001

visual-studio-2019 - -d.lib 和普通的 SFML-system.lib 有什么不同?

c++ - SFML 获取全屏模式

c++ - 如何验证字符串是否是 C++ 中的有效 IPv4 地址?

c++ - 为什么我在检查核心转储时进入 gdb "Cannot access memory at address 0x..."?

c++ - 作为 TabWidget 的可 ScrollView

c++ - 返回值为const引用时如何返回 "not found"

c++ - 如何在任何类中使用 Objects form main? C++

c++ - 声明 sf::SoundBuffer 会导致程序在终止时崩溃