1
\$\begingroup\$

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;

    tex.SetData(data);

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

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

    tex.Dispose();
}

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?

\$\endgroup\$
2
  • \$\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, 2018 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\$ Oct 10, 2018 at 12:16

1 Answer 1

-1
\$\begingroup\$

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)
            InitializePixel(spriteBatch);

        spriteBatch.Draw(Pixel, rect, color);
    }
}  
\$\endgroup\$
1
  • 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\$ Oct 10, 2018 at 10:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .