window 上未绘制 SFML 文本

SFML Text is not drawn on the window

我在 C++ 中使用 SFML。问题是如果我使用函数,window 上什么也没有绘制,但是当我将文本设为本地时我可以绘制。请告诉我我做错了什么

代码:

在game.cpp文件中

void Game::loadMenuText(sf::Font f, std::string textString, int x, int y, sf::Text *tex){

tex->setFont(f);
tex->setCharacterSize(16);
tex->setFillColor(sf::Color(0x225522ff));
tex->setStyle(sf::Text::Bold);
tex->setString(textString);
tex->setPosition(x,y);

}

void Game::loadFont(){

if (!font.loadFromFile("font/arial.ttf"))
{
    std::cout<<"Font could not be loaded";
}

}

void Game::run(){
    loadFont();
    sf::Text ButtonTex;
    loadMenuText(font,"Play",20,20,&ButtonTex);
    menuText.push_back(ButtonTex);
    window.draw(menuText[0]);

}

在 game.hpp 文件中

private:
sf::Font font;
std::vector<sf::Text> menuText;
public:
void run();
void loadFont();
void loadMenuText(sf::Font, std::string, int, int, sf::Text *tex);

希望我没有忘记添加任何内容

阅读有关 Text

的参考资料

It is important to note that the sf::Text instance doesn't copy the font that it uses, it only keeps a reference to it. Thus, a sf::Font must not be destructed while it is used by a sf::Text (i.e. never write a function that uses a local sf::Font instance for creating a text).

你的问题是你将函数 loadMenuText 中的局部变量 sf::Font f 传递给 tex 所以它导致未定义的行为, tex 指的是被删除的资源.

将您的签名更改为:

void Game::loadMenuText(sf::Font& f, std::string textString, int x, int y, sf::Text *tex){    
                                 ^^^ 
 //..

那么您将使用原始 font 对象而不是它的副本。