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

All I want is to clear my renderTarget2D once so that it starts out completely transparent and then preserves its content between frames.

I am drawing the renderTarget texture after painting the background texture, so I don't want it to paint. However, Clear (Color.Transparent) it renders as opaque purple, which I understand is the default transparent color ...

What am I doing wrong? I tried to change the SurfaceFormat parameter in the constructor, but it 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);

      

+3


source to share


1 answer


RenderTarget2D is used to render objects off the screen, which indicates that your sample code is not drawing anything to the screen. Use the sprite command to draw the RenderTarget2D in a back buffer that will affect the rendering.

Another problem is that by drawing a completely transparent RenderTarget2D you are not going to change anything on the screen, so even if the code works by creating a rendertarget, clearing it with transparency, and drawing it does not affect the screen.



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

        _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()

      

+3


source







All Articles