Timmos
Timmos

Reputation: 3324

Extract an SDL_Texture from a source SDL_Texture

I have the following function that extracts a 64x64 pixel texture from a bigger texture tiled with them:

SDL_Texture* cropTexture (SDL_Texture* src, int x, int y)
{
    SDL_Texture* dst = SDL_CreateTexture(gRenderer, gSurface->format->format, SDL_TEXTUREACCESS_TARGET, 64, 64);
    SDL_Rect rect = {64 * x, 64 * y, 64, 64};
    SDL_SetRenderTarget(gRenderer, dst);
    SDL_RenderCopy(gRenderer, src, &rect, NULL);

    return dst;
}

Now, when I call the function like this:

SDL_Texture* txt_walls [3];
txt_walls[0] = cropTexture (allWalls, 0, 0);
txt_walls[1] = cropTexture (allWalls, 0, 1);
txt_walls[2] = cropTexture (allWalls, 4, 3);

then txt_walls[2] results in a black texture (or at least, uninitialized).

When I add one meaningless line of code to that:

SDL_Texture* txt_walls [3];
txt_walls[0] = cropTexture (allWalls, 0, 0);
txt_walls[1] = cropTexture (allWalls, 0, 1);
txt_walls[2] = cropTexture (allWalls, 4, 3);
cropTexture (allWalls, 1, 1); // whatever, ignore the returned object

then txt_walls[2] is correct: the texture at this array position renders just fine in my program.

What is wrong with cropTexture? I'm new in both C++ and SDL2.

Upvotes: 0

Views: 264

Answers (1)

user5257014
user5257014

Reputation:

You need to set the render target back to default after you have cropped the texure, otherwise it will continue to draw on the texture. Add this before the return in cropTexture:

SDL_SetRenderTarget(gRenderer, NULL);

Upvotes: 1

Related Questions