Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating texture to fit certain size in SFML

Tags:

sfml

I have a file that contains textures. I load it to sf::Texture and split into sprites with setTextureRect.

Now lets say one sprite contains part of texture that is 20 pixels wide. How can I render it to fit width of e.g. 213 pixels. The only way I can think about is to render it to sf::RenderTexture and crop it with another sprite.

Is there a better way to do this?

like image 835
TPlant Avatar asked Oct 22 '14 21:10

TPlant


1 Answers

You can use sf::Texture::setRepeated to do that.

However, you'll need to copy that part of your bigger image into an independant texture.

Here is an example:

#include <SFML/Graphics.hpp>

int main(int, char const**)
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");

    sf::Image img;
    img.create(20, 20);
    for (auto i = 0; i < 20; ++i) {
        for (auto j = 0; j < 20; ++j) {
            img.setPixel(i, j, sf::Color(255 * i / 20, 255 * j / 20, 255 * i / 20 * j / 20));
        }
    }

    sf::Texture texture;
    texture.loadFromImage(img);
    texture.setRepeated(true);

    sf::Sprite sprite;
    sprite.setTexture(texture);
    sprite.setTextureRect({ 0, 0, 800, 600 });

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                window.close();
            }

            if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
                window.close();
            }
        }

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

    return EXIT_SUCCESS;
}

enter image description here

like image 151
Hiura Avatar answered Nov 09 '22 18:11

Hiura