c++ - SFML 文本未绘制在窗口上

标签 c++ sfml

我在 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/

相关文章:

c++ - DCMTK 字符集 Unicode 错误

C++11 基本构造函数使用 "using"关键字委托(delegate)/转发到派生类

c++ - 如何在 Geany IDE 中增加行填充?

c++ - 防止文本文件在函数中删除但保持写入它的能力? C++

c++ - 如何关闭 CPPUnit 中的单元测试

c++ - 在游戏循环中使用 sleep() 会使增量时间不稳定

c++ - SFML - 尝试从 vector 绘制 Sprite 时程序崩溃

c# - 带 C# 的 SFML,启动麻烦

c++ - sfml 2 和 cmake 构建

c++ - 我可以在 C++ 中有一个 "type of types"吗?