Search code examples
bitmapxnadrawingprimitivetexture2d

Working with primitives in XNA


Perhaps I am trying to use XNA in a way that it was not designed, but I would very much like to be able to draw my own primitives and save them as a bitmap, or a texture2D, or anything that will hold a few 2d lines for me. My goal is to program a game where the textures are created procedurally, instead of just being loaded from the content manager.

If it helps to know, I've made a Shape class that stores polygons, and I probably could just tell spriteBatch to draw each line out, but I'm trying to optimize by storing commonly used shapes somewhere, instead.


Solution

  • You can use a RenderTarget for your task. Something like this:

    // var to store your drawing
    Texture2D newShape;
    
    // drawing will be on this target
    RenderTarget2D rt = new RenderTarget2D(GraphicsDevice, width, height);
    SpriteBatch sb = new SpriteBatch(GraphicsDevice);
    
    // set to render all to render target
    GraphicsDevice.SetRenderTarget(rt); 
    
    GraphicsDevice.Clear(Color.Transparent); 
    
    sb.Begin();
    
    // Draw what you want here.
    
    sb.End()
    
    // Return to drawing on "main" buffer
    GraphicsDevice.SetRenderTarget(null);
    
    // Save the texture you just drawn
    newShape = rt;