RenderTarget2D Class

Represents a 2D texture resource that will be written to at the end of a render pass.

Namespace: Microsoft.Xna.Framework.Graphics
Assembly: Microsoft.Xna.Framework (in microsoft.xna.framework.dll)

public class RenderTarget2D : RenderTarget

After a render pass the render target contains the color information of a rendered image.

Render targets represent a linear area of display memory and usually reside in the display memory of the display card. Because of this, RenderTarget2D objects must be recreated when the device is reset.

To use a RenderTarget2D, you must:

  1. Create the RenderTarget2D.
    shadowRenderTarget = GfxComponent.CreateRenderTarget(GraphicsDevice,
        1, SurfaceFormat.Single);
    public static RenderTarget2D CreateRenderTarget(GraphicsDevice device, int numberLevels,
        SurfaceFormat surface)
        MultiSampleType type = device.PresentationParameters.MultiSampleType;
        // If the card can't use the surface format
        if (!GraphicsAdapter.DefaultAdapter.CheckDeviceFormat(DeviceType.Hardware,
            GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Format, TextureUsage.None,
            QueryUsages.None, ResourceType.RenderTarget, surface))
            // Fall back to current display format
            surface = device.DisplayMode.Format;
        // Or it can't accept that surface format with the current AA settings
        else if (!GraphicsAdapter.DefaultAdapter.CheckDeviceMultiSampleType(DeviceType.Hardware,
            surface, device.PresentationParameters.IsFullScreen, type))
            // Fall back to no antialiasing
            type = MultiSampleType.None;
        int width, height;
        // See if we can use our buffer size as our texture
        CheckTextureSize(device.PresentationParameters.BackBufferWidth, device.PresentationParameters.BackBufferHeight,
            out width, out height);
        // Create our render target
        return new RenderTarget2D(device,
            width, height, numberLevels, surface,
            type, 0);
  2. Set the RenderTarget2D.
    GraphicsDevice.SetRenderTarget(0, shadowRenderTarget);
  3. Draw into the RenderTarget2D.
    // Render the shadow map
  4. Reset the original RenderTarget2D. null as the default render target - i.e. the back buffer.
    // Set render target back to the back buffer
    GraphicsDevice.SetRenderTarget(0, null);
  5. Call GetTexture to retrieve the contents of the RenderTarget2D.
    // Return the shadow map as a texture
    return shadowRenderTarget.GetTexture();

Xbox 360, Windows XP SP2, Windows Vista, Zune

Community Additions