I use the following method to draw a box onto the screen:

private void DrawBox(Rectangle rect, Color color, Vector2 offset)
    Texture2D tex = new Texture2D(GraphicsDevice, rect.Width, rect.Height);
    Color[] data = new Color[rect.Width * rect.Height];

    for (int i = 0; i < data.Length; i++)
        data[i] = color;


    var pos = new Vector2(rect.Location.X, rect.Location.Y) + offset;

    spriteBatch.Draw(tex, pos, Color.White);


However, this results in a completely black image being drawn onto the screen, regardless of the colour I pass to this method. Why is this happening and how can I fix this?

  • \$\begingroup\$ I'll say that this is a terrible way to draw a colored rectangle. Just create a 1px * 1px white texture and pass in the color as the color argument for the draw method of the spritebatch \$\endgroup\$ – Bálint Aug 26 '18 at 16:34
  • \$\begingroup\$ This is something of a guess, as I'm not particularly familiar with XNA but in similar systems the SpriteBatch.draw doesn't actually draw, that happens later. I suspect that by Disposing of your texture immediately after the call, you are destroying the data needed to plot it correctly before it is actually being drawn. \$\endgroup\$ – Jack Aidley Oct 10 '18 at 12:16

You can draw a box using a precreated white pixel (1x1) texture and then draw this pixel using default spriteBatch.Draw method. Here's an example:

public static class Primitives
    private static Texture2D Pixel;

    private static void InitializePixel(SpriteBatch spriteBatch)
        Pixel = new Texture2D(spriteBatch.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
        Pixel.SetData(new [] { Color.White });

    public static void DrawBox(this SpriteBatch spriteBatch, Rectangle rect, Color color)
        if (Pixel == null)

        spriteBatch.Draw(Pixel, rect, color);
  • 1
    \$\begingroup\$ I don't think this answers the question, I believe the asker is simply applying a simple test case while trying to get Texture2D to work rather than trying to display a rectangle. This answer neither explains why their approach isn't working nor offers a solution. \$\endgroup\$ – Jack Aidley Oct 10 '18 at 10:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.