我在 C++ 中使用 SFML。问题是如果我使用函数,窗口上什么也不会画,但是当我将文本设为本地时我可以画画。请告诉我我做错了什么
代码:
在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
对象而不是它的拷贝。
关于c++ - SFML 文本未绘制在窗口上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52927566/