How to draw a render target onto an existing image on backbuffer without overwriting?

I’m trying to draw a render target to the back buffer:

spriteBatch.GraphicsDevice.SetRenderTarget(renderTarget);
spriteBatch.GraphicsDevice.Clear(Color.Transparent);
spriteBatch.Begin(SpriteSortMode.Deferred,
                BlendState.AlphaBlend,
                SamplerState.LinearClamp,
                DepthStencilState.None,
                RasterizerState.CullNone,
                null);
spriteBatch.Draw(renderTarget, Vector2.Zero, Color.White * TransitionAlpha);

The backbuffer already has something drawn on it and I want the render target to blend in without overwriting it. But the result is that the render target completely replaced the image on the backbuffer (transparent part turned purple). How can I solve this issue?

This is the code to fill the renderTarget. But how do you draw renderTarget onto the backbuffer ?
Also you should have triggered an exception when setting the renderTarget and also drawing it without calling SetRenderTarget(null)

Oh I pasted it wrong. It should be:

spriteBatch.GraphicsDevice.SetRenderTarget(renderTarget);
spriteBatch.GraphicsDevice.Clear(Color.Transparent);
spriteBatch.Begin(SpriteSortMode.Deferred,
                BlendState.AlphaBlend,
                SamplerState.LinearClamp,
                DepthStencilState.None,
                RasterizerState.CullNone,
                null);
\\Draw stuff onto the render target
spriteBatch.End();

spriteBatch.GraphicsDevice.SetRenderTarget(null);
spriteBatch.Begin(SpriteSortMode.Deferred,
                BlendState.AlphaBlend,
                SamplerState.LinearClamp,
                DepthStencilState.None,
                RasterizerState.CullNone,
                null);
spriteBatch.Draw(renderTarget, Vector2.Zero, Color.White * TransitionAlpha);
spriteBatch.End();

Sorry about the copy-and-paste mess…

As far as I know the act of switching to a RenderTarget clears it to a purple color as long as you haven’t set the RenderTargetUsage to something else than ‘DiscardContents’, which is the default-setting because of performance reasons.
And the backbuffer counts as a RenderTarget.

See here for details:


or here:
http://what-when-how.com/xna-game-studio-4-0-programmingdeveloping-for-windows-phone-7-and-xbox-360/render-targets-xna-game-studio-4-0-programming/

So you shouldn’t do that. Instead you should draw all the parts you’d like to have to show up on the backbuffer into separate RenderTargets and then, finally, switch to the backbuffer and draw all those RenderTargets consecutively.

Hope that helps,
Psilo

Got it. I’ll modify my code. Thanks bro!

Make sure the render target was created with a SurfaceFormat that has an alpha channel and clear it to Color.Transparent first before drawing anything to it. Then draw it to the back buffer using BlendState.NonPremultiplied because it won’t have premultiplied alpha.

Thanks very much for your help @KonajuGames! :smile: