Search code examples
c++imagerenderingshapessfml

How to Render images in shape/ polygon form?


Hey i'm working with SFML right now, and upon finishing the tutorials i still do not know how to give a shape a texture or image, and not just a solid color/outline.

The only thing i know can take an image is a sprite, but thats WAY to simple, as it only allows you to render rectangular images in a rectangluar way!

What are the tecniques for rendering images onto shapes, and ONLY inside the shape? It would be great if some of you could provide some resources or SFML-specific stuff!


Solution

  • SFML has been updated since this question was originally answered and you can now add textures to shapes easily. The shape class has the setTexture() and setTextureRect() methods. setTexture() takes a pointer to an sf::Texture. See the documentation.

    Sf::Texture texture;
    if (!texture.loadFromFile("mytexture.png"))
    {
        std::cerr << "failed to load";
    }
    sf::RectangleShape myRect{ sf::Vector2f(width, height) };
    myRect.setTexture(&texture);
    myRect.setTextureRect(sf::IntRect( x, y, width, height ));