user2030677
user2030677

Reputation: 3526

Why is my sprite not displaying?

I have a simple program where I set the texture of a sprite and change its color, but it won't display. The window is entirely black. Is there something I did not do?

#include <SFML/Graphics.hpp>

int main()
{
    sf::Texture texture;
    sf::Sprite sprite;

    texture.create(200, 200);

    sprite.setTexture(texture);
    sprite.setColor(sf::Color(209, 59, 59));

    while (window.isOpen())
    {
        window.clear();
        window.draw(sprite);
        window.display();
    }

    return 0;
}

Upvotes: 0

Views: 137

Answers (1)

Foxar
Foxar

Reputation: 56

Setting a color to a sprite while its texture's pixels have no color will not work, because of how sf::Sprite::setColor() method works.

From SFML documentation:

void sf::Sprite::setColor ( const Color & color )

This color is modulated (multiplied) with the sprite's texture. It can be used to colorize the sprite, or change its global opacity. By default, the sprite's color is opaque white.

Multiplying any color against a transparent texture will not change anything in how the Sprite is rendered.

One solution would be to create an image of size 200,200 and setting the image to the desired color, using sf::Image::create (width, height, color) constructor, then loading the texture from that image.

Example code:

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(500,500), "TEST");

    sf::Image image;
    image.create(200,200,(sf::Color(209, 59, 59)));

    sf::Texture texture;
    texture.loadFromImage(image);

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

    while (window.isOpen())
    {
        window.clear();
        window.draw(sprite);
        window.display();
    }

    return 0;
}

Upvotes: 1

Related Questions