kbirk
kbirk

Reputation: 4022

C# XNA renderTarget2D .Clear(Color.Transparent) not working

All I want is to clear my renderTarget2D once so that it starts off compeltely transparent, and then preserve it's contents between frames.

I draw the renderTarget texture after I draw the background texture, so I don't want it to paint over. However Clear(Color.Transparent) it shows up as an opaque purple, which as I understand is the default clear color...

What am I doing wrong? I tried changing the SurfaceFormat parameter in the constructor but that had no effect. what am I doing wrong?

// instantiate renderTarget to preserve contents
renderTarget = new RenderTarget2D(GraphicsDevice,
                                   GraphicsDevice.PresentationParameters.BackBufferWidth,
                                   GraphicsDevice.PresentationParameters.BackBufferHeight,
                                   false,
                                   GraphicsDevice.PresentationParameters.BackBufferFormat,
                                   DepthFormat.Depth24,
                                   0,
                                   RenderTargetUsage.PreserveContents);
// clear with transparent color
GraphicsDevice.SetRenderTarget(Globals.renderTarget);
GraphicsDevice.Clear(Color.Transparent);
GraphicsDevice.SetRenderTarget(null);

Upvotes: 4

Views: 7195

Answers (1)

ClassicThunder
ClassicThunder

Reputation: 1936

RenderTarget2D is used to draw things off screen which brings up the fact that your code sample is drawing nothing to the screen. Use the sprite batch to actually draw the RenderTarget2D to the back buffer which will effect the display.

Another problem being that by drawing a fully transparent RenderTarget2D is you are not going to change anything on screen so even if you code was working creating a rendertarget, clearing it with transparency, and drawing it effects nothing on the screen.

Below is an example of using a render target then drawing that rendertarget on screen. You usually don't want to use rendertargets unless you have very costly drawing operations that are static so you can render them once to the rendertarget and reuse them. Or bacause you wan't to isolate a scene to run a shader on.

        _renderTarget = new RenderTarget2D(
            GraphicsDevice, 
            (int)size.X, 
            (int)size.Y);

        GraphicsDevice.SetRenderTarget(_renderTarget);
        GraphicsDevice.Clear(Color.Transparent);

        SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);

        //draw some stuff.

        SpriteBatch.End()

        GraphicsDevice.SetRenderTarget(null);

        GraphicsDevice.Clear(Color.Blue);

        SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);

        SpriteBatch.Draw(_renderTarget, Vector2.Zero, Color.white);

        SpriteBatch.End()

Upvotes: 3

Related Questions