SFML community forums

Help => Graphics => Topic started by: Steeling on February 06, 2023, 08:18:12 pm

Title: Texture.update doesn't work as expected
Post by: Steeling on February 06, 2023, 08:18:12 pm
Hello everyone,

First of all please forgive my English as it is not my mother tongue  ;D

I'm trying to conceive a very simple code to begin with SFML : displaying an image, then, after a click on it, setting the pixel clicked color in blue.

Unfortunately, when I click, nothing happens and I have no idea why. I've displayed the pixels values (RGB) in the CLI before and after the click, I see that the values are different (so the color has been modified) but the picture isn't modified. So I think that the problem comes from my use of the update fonction. I have read the documentation several times and I still don't know what I am doing wrong.

Thanks in advance for any help !

You can find my code below :

sf::Image fill_shape(int x, int y, sf::Image img){

    sf::Image new_image = img;
    new_image.setPixel(x, y, BLUE);
    return new_image;
}

int main()
{
    // Load an image file from a file
    sf::Texture texture;
    if (!texture.loadFromFile("image.jpg")){
        return EXIT_FAILURE;
    }
    sf::Sprite sprite(texture);

    int x = sprite.getTexture()->getSize().x * sprite.getScale().x;
    int y = sprite.getTexture()->getSize().y * sprite.getScale().y;
    sf::RenderWindow window(sf::VideoMode(x, y), "Image Filler");

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed){
                window.close();
            }
            else if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
            {
                sf::Vector2i position = sf::Mouse::getPosition();
                int x = position.x;
                int y = position.y;
                sf::Image image = sprite.getTexture()->copyToImage();
                sf::Image new_image = fill_shape(x, y, image);
                texture.update(new_image);
                sprite.setTexture(texture);
            }
        }

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

    return 0;
}
Title: Re: Texture.update doesn't work as expected
Post by: kojack on February 07, 2023, 12:06:43 am
sf::Mouse::getPosition() gives you the coordinates of the mouse on the monitor, with 0,0 in the top left corner. But if your window is smaller than the monitor and placed in the middle, it won't match.
So when you go to set a pixel, the coordinates are probably too large and outside of the window.

You can get the coordinates inside of the window by doing:
sf::Mouse::getPosition(window)
Title: Re: Texture.update doesn't work as expected
Post by: Steeling on February 07, 2023, 01:26:20 pm
Hello,

Thanks for your answer !

I've tested it and you are totally right ! I was totally missing the point !

Thank you so much :)