在SFML中加载纹理

3

我开始学习SFML,我想创建一个精灵来从文件中加载图像,所以我只是按照教程做了明显的事情。

sf::Texture texture;
texture.loadFromFile("C:\image.png");

sf::Sprite sprite;
sprite.setTexture(texture);
window.draw(sprite);

当我启动程序时,只会出现一个白屏和“Unhandled exception at 0x50CEDEDA (msvcr110.dll) in itsprgps.exe: 0xC0000005: Access violation reading location 0x00524000.”的错误信息,而且控制台中也会充满随机符号。我尝试查找一些信息,但只找到了“If the texture is destroyed or moves elsewhere in memory, the sprite ends up with an invalid texture pointer”这个提示,对于一些人来说可能很明显,但我是新手,他们没有给出任何可行的示例。
我使用的是SFML 2.1和Visual Studio 2013。
编辑:
以下是我的代码示例,在尝试加载纹理之前,我画了所有形状:
int main()
{
 sf::RenderWindow window(sf::VideoMode(557, 500), "My window");

while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
    }

    window.clear(sf::Color(255, 255, 255));

    sf::Texture texture;
    texture.loadFromFile("C:\roads.png");

    sf::Sprite sprite;
    sprite.setTexture(texture);
    window.draw(sprite);

    window.display();
}

return 0;
}

我还发现了另外一件事... 我也无法加载字体,发生的情况完全相同,我想我知道原因了。当我开始这个项目时,我添加了发布库而不是调试库("sfml-system.lib;sfml-main.lib;sfml-graphics.lib;sfml-window.lib;" 而不是 "sfml-system-d.lib;sfml-main-d.lib;sfml-graphics-d.lib;sfml-window-d.lib;"),所以我认为这可能是问题所在,于是我试图解决它,但我又遇到了另一种问题。
简而言之:我尝试了适合调试和发布的正确配置,但我得到了不同的错误,首先,我缺少一个 MSVCR110D.dll,出于好奇心,我下载了它并放在了调试文件夹中,现在我得到了 0xc000007b 的错误。我尝试了不同的配置,唯一有效的是使用发布库进行调试(迄今为止除了尝试加载纹理或字体)。

loadFromFile返回一个bool类型的值。请检查返回值以确定加载是否成功。 - tillaert
问题可能出在window的初始化上,请提供一个最小可编译示例以重现问题。 - tillaert
在原帖中添加了示例,还添加了一些注释,请查看。 - delca7
混合使用调试/发布配置是不好的... http://stackoverflow.com/a/20215509/520217 - Hiura
是的,我意识到了,但我似乎遇到了一些问题,我认为我的系统缺少一些重要的文件或其他东西。 - delca7
如何解决0xc000007b或MSVCR110D.dll的问题? - delca7
4个回答

3

("C:\image.png"); 改为 ("C:\\image.png");

很可能是单个反斜杠导致的问题,因为它是一个转义字符。

此外,您应该检查从 loadFromFile 返回的值以确保加载成功。


反斜杠不是问题,loadFromFile的结果为true。 - delca7

2
我建议您将负责加载纹理的代码移出循环,并检查其返回值。即使这不会解决问题,您也可以遇到或排除与多个加载图像相关的任何问题。
代码:
int main()
{
    sf::RenderWindow window(sf::VideoMode(557, 500), "My window");
    
    sf::Texture texture;
    if(!texture.loadFromFile("C:\roads.png"))
    {
        std::cerr << "failed to load image" << std::endl;
        exit(1);
    }

    sf::Sprite sprite;
    sprite.setTexture(texture);

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear(sf::Color(255, 255, 255));
        window.draw(sprite);
        window.display();
    }
}

0

看起来你需要安装适用于你的 Visual Studio 版本的 Visual C++ Redistributable,你可以在 Microsoft 的网站上下载。


0

当在调试模式下的“链接器输入”配置中时,请确保将“-d”添加到附加文件中!

例如:sfml-system-d.lib


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接