【问题标题】:Displaying text from a sf::Text object from another Class. SFML显示来自另一个类的 sf::Text 对象的文本。 SFML
【发布时间】:2017-08-24 18:15:27
【问题描述】:

我正在尝试创建一个类,该类将创建一个带有一些白色文本的黑框。它最终将能够根据发送到类的字符串来缩放框的大小。但是,首先,我不知道为什么文本不显示。我很感激帮助。

这是 TextBox.h

class TextBox{

public:

sf::RectangleShape rect;
sf::Text text;
sf::Font font;

TextBox(std::string str, sf::Font f);
sf::Text getText();

这是在 TextBox.cpp 中找到的 TextBox 构造函数。我发送给构造函数的 sf::Font 是 SFML 设置的字体。

#include "TextBox.h"
#include "string"

TextBox::TextBox(std::string str, sf::Font font){

rect.setFillColor(sf::Color::Black);
rect.setPosition(20, 20);
rect.setSize(sf::Vector2f(120,120));

text.setFont(font);
text.setString(str);
text.setCharacterSize(24);
text.setFillColor(sf::Color::White);

text.setPosition(rect.getPosition());

}

这是 main.cpp 中的代码,应该同时显示 Rect 和 Text

sf::Font font;
if (!font.loadFromFile(resourcePath() + "sansation.ttf")) {
    return EXIT_FAILURE;
}

TextBox textBox("This Box", font);
textBox.text.setStyle(sf::Text::Bold);
// Start the game loop
while (window.isOpen())
{
    // Process events
    sf::Event event;
    while (window.pollEvent(event))
    {
        // Close window: exit
        if (event.type == sf::Event::Closed) {
            window.close();
        }

        // Escape pressed: exit
        if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
            window.close();
        }
    }

    // Clear screen
    window.clear();

    window.draw(textBox.rect);
    window.draw(textBox.text);

    // Update the window
    window.display();

我尝试使用返回 sf::Text 对象的公共 getText() 方法,但它并没有解决问题。 此外,我对 rect 所做的修改确实有效,并且显示了 rect。文字不是。

谢谢你,干杯

【问题讨论】:

标签: c++ xcode sfml


【解决方案1】:

来自sf::Text::setFont() method

字体参数指的是只要文本使用它就必须存在的字体。实际上,文本不存储它自己的字体副本,而是保留一个指向您传递给此函数的字体的指针。如果字体被破坏并且文本尝试使用它,则行为未定义。

.

在您的TextBox 构造函数中,您将font 作为副本f 传递,在初始化textBox 后,字体副本f 将被销毁,因此您的textBox.text 不会显示。

修复它很简单:使用传递(常量)引用传递fontTextBox(std::string str, const sf::Font& f);

(您可能也想将 std::string 作为 const 引用传递)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-07
    • 2014-06-13
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多