8

i am having trouble with the following:

I need to render a texture on top of another texture and then render that main texture. For example I have the blue rectangle texture, and I want to draw red rectangles on top of this blue rect. However i want them to restrict the render only on this rectangle. Like the following image: enter image description here

I read something about texture blit between them or something like that but im not sure if this is posible.

My code looks like this:

SDL_RenderCopy(ren,bluetexture,NULL,dBLUErect);
SDL_RenderCopy(ren,redtexture,NULL,dREDrect);
SDL_RenderPresent(ren);

Any one knows about how to do this in SDL 2.0? thats what Im using by the way.

chelo_c
  • 1,739
  • 3
  • 21
  • 34

2 Answers2

12

Mars answer didnt work because it drew a black texture and nothing could be drawn on that.

But THIS WORKS!:

SDL_Texture* auxtexture = SDL_CreateTexture(ren, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, 500, 500);

//change the rendering target

SDL_SetTextureBlendMode(auxtexture, SDL_BLENDMODE_BLEND);
SDL_SetRenderTarget(ren, auxtexture);

//render what we want
triangle->render(ren); //render my class triangle e.g


//change the target back to the default and then render the aux

SDL_SetRenderTarget(ren, NULL); //NULL SETS TO DEFAULT
SDL_RenderCopy(ren, auxtexture, NULL, canvas->drect);
SDL_DestroyTexture(auxtexture);

Cheers.

chelo_c
  • 1,739
  • 3
  • 21
  • 34
  • 3
    Some tips for future readers. Always make sure you initialize your `SDL_Renderer` with the `SDL_RENDERER_TARGETTEXTURE` flag to support render targets. Also, never try to use a `SDL_Texture` that was created from a `SDL_Surface` using the `SDL_CreateTextureFromSurface` function. It just won't work. – Justin Skiles Feb 26 '14 at 03:51
  • @JustinSkiles I'm glad someone noticed the lack of SDL_RENDERER_TARGETTEXTURE, for a brief moment I thought either I'd gone crazy or the api had suddenly changed to allow all renderers to render straight to render target textures. – Pharap Apr 17 '14 at 22:22
  • I couldn't understand what happens here. Please, somebody, explain? What is the triangle->render(). How does this function work, and where is the code for this function? What is SDL function call inside this function? – R Nanthak Jun 23 '20 at 08:20
4

First, you need to create your texture on which you want to draw with SDL_TEXTUREACCESS_TARGET flag. So create back texture like this:

back = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, 50, 50);

Then, when calling drawing functions, you need to set the back texture as the target, like so:

SDL_SetRenderTarget(renderer, back);

Then you draw what you want, and after that you change the target to null:

SDL_SetRenderTarget(renderer, NULL);

And render back texture:

SDL_RenderCopy(renderer, back, NULL, &some_rect);
Mars
  • 867
  • 2
  • 13
  • 22