Drawing images in SFML

In order to draw an image on screen, we need to become familiar with two classes: sf::Texture and sf::Sprite. A texture is essentially just an image that lives on the graphics card for the purpose of making it fast to draw. Any given picture on your hard drive can be turned into a texture by loading it:

sf::Texture texture;
if(!texture.loadFromFile("filename.png"){
    // Handle an error.
}

The loadFromFile method returns a Boolean value, which serves as a simple way of handling loading errors, such as the file not being found. If you have a console window open along with your SFML window, you will notice some information being printed out in case the texture loading did fail:

Failed to load image "filename.png". Reason : Unable ...

Get SFML Game Development By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.