user1816388
user1816388

Reputation: 73

How can I make this function return a sf::Texture? SFML2.0

void TileSheetManager::setTileSheet(const string textureName)
{
    texture.loadFromFile(textureName);
}

sf::Sprite TileSheetManager::getTile(int left, int top, int width, int height)
{

    sf::IntRect subRect;
    subRect.left = left * 32;
    subRect.top = top * 32;
    subRect.width = width;
    subRect.height = height;

    sf::Sprite sprite(texture, subRect);

    return sprite;
}

I need getTile() to return a sf::Texture yet I have no idea how I could do it.
I'm using SFML2.0 by the way.

Upvotes: 0

Views: 1244

Answers (2)

Aesthete
Aesthete

Reputation: 18848

The method getTile that you have at the moment does what it's supposed to. You have a tile management class that loads an entire spritesheet, and hands out cropped areas as sprites. Don't change this method just to solve this problem, your TileSheetManager class is structured well.

If you want to convert one of your sprites to a texture, you could try the following.

// Get a sprite from the Tile Manager.
sf::Sprite mySprite = tileSheetMgr.getTile(1,2,3,4);
// Create a new texture for the sprite returned.
sf::Texture spriteTexture;
// Generate the texture from the sprite's image.
spriteTexture.loadFromImage(*mySprite.getImage());

Upvotes: 2

emartel
emartel

Reputation: 7773

According to the documentation here and here you should be able to

sf::Image fullImage = texture.copyToImage();
sf::Image croppedImage(width, height);
croppedImage.copy(fullImage, 0, 0, subRect);
sf::Texture returnTexture();
returnTexture.LoadFromImage(croppedImage);

Upvotes: 2

Related Questions