Sam
Sam

Reputation: 1230

SFML image not loading

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: enter image description here

directory: enter image description here

Thank you

Upvotes: 3

Views: 4969

Answers (3)

Hiura
Hiura

Reputation: 3530

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.

Upvotes: 1

nvoigt
nvoigt

Reputation: 77364

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;
}

Upvotes: 2

Nayd
Nayd

Reputation: 99

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>))

Upvotes: 2

Related Questions