SFML image not loading

六眼飞鱼酱① 提交于 2019-12-14 01:23:13

问题


I am using Xcode with SFML. I placed my file in the Xcode project which copied it to the directory. However, I still am unable to load it into the program. Any ideas?

Code:

int main(int argc, const char * argv[])
{
    sf::RenderWindow(window);
    window.create(sf::VideoMode(800, 600), "My window");

    sf::Texture img;
    if(!img.loadFromFile("colorfull small.jpg")) return 0;

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

    window.draw(sprite);
    window.display();

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

compiler:

directory:

Thank you


回答1:


There are a couple reasons for the error:

From sfml documentation:

Some format options are not supported, like progressive jpeg.

or

It doesn't find the file because the filename has spaces in it (rename the file, e.g colorfull_small.jpg)

or

The program's working directory does not have the .jpg file (you can print it using getcwd(NULL) (available in #include <unistd.h>))




回答2:


I'm somewhat surprised that the "correct answer" has a comment saying that it's not working... anyway:

Your rendering (drawing) need to take place in every iteration of your loop:

int main(int argc, const char * argv[])
{
    sf::RenderWindow(window);
    window.create(sf::VideoMode(800, 600), "My window");

    sf::Texture img;
    if(!img.loadFromFile("colorfull small.jpg")) return 0;

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

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

        // drawing needs to take place every loop right HERE 
        window.clear();
        window.draw(sprite);
        window.display();
    }

    return 0;
}



回答3:


Quoting the official tutorial:

the project comes with a basic example in main.cpp and a helper function: std::string resourcePath(void); in ResourcePath.hpp and ResourcePath.mm. The usefulness of this function, as illustrated in the provided example, is to get in a convenient way access to the Resources folder of your application bundle.

This means you have to write something like:

#include "ResourcePath.hpp"
:
:
if (!icon.loadFromFile(resourcePath() + "colorfull small.jpg")) {
:
:

(Inspired by the default code generated by the project template.)

nvoigt's answer is also very important.



来源:https://stackoverflow.com/questions/20203108/sfml-image-not-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!