18
votes

I am trying to draw a rectangle shape in XNA using spritebatch. I have the following code:

        Texture2D rect = new Texture2D(graphics.GraphicsDevice, 80, 30);
        Vector2 coor = new Vector2(10, 20);
        spriteBatch.Draw(rect, coor, Color.Chocolate);

But it doesn't draw anything for some reason. Any idea what's wrong? Thanks!

3
You can find another solution here: stackoverflow.com/questions/2792694/draw-rectangle-with-xna/… It involves creating an extended version of SpriteBatch.wronex

3 Answers

44
votes

Here is code that you could put into a class derived from Game. This demonstrates both where and how to create a white, 1-pixel-square texture (plus how to dispose of it when you are done). And how you can then scale and tint that texture at draw time.

For drawing flat-coloured rectangles, this method is preferable to creating the texture itself at the desired size.

SpriteBatch spriteBatch;
Texture2D whiteRectangle;

protected override void LoadContent()
{
    base.LoadContent();
    spriteBatch = new SpriteBatch(GraphicsDevice);
    // Create a 1px square rectangle texture that will be scaled to the
    // desired size and tinted the desired color at draw time
    whiteRectangle = new Texture2D(GraphicsDevice, 1, 1);
    whiteRectangle.SetData(new[] { Color.White });
}

protected override void UnloadContent()
{
    base.UnloadContent();
    spriteBatch.Dispose();
    // If you are creating your texture (instead of loading it with
    // Content.Load) then you must Dispose of it
    whiteRectangle.Dispose();
}

protected override void Draw(GameTime gameTime)
{
    base.Draw(gameTime);
    GraphicsDevice.Clear(Color.White);
    spriteBatch.Begin();

    // Option One (if you have integer size and coordinates)
    spriteBatch.Draw(whiteRectangle, new Rectangle(10, 20, 80, 30),
            Color.Chocolate);

    // Option Two (if you have floating-point coordinates)
    spriteBatch.Draw(whiteRectangle, new Vector2(10f, 20f), null,
            Color.Chocolate, 0f, Vector2.Zero, new Vector2(80f, 30f),
            SpriteEffects.None, 0f);

    spriteBatch.End();
}
20
votes

Your texture doesn't have any data. You need to set the pixel data:

 Texture2D rect = new Texture2D(graphics.GraphicsDevice, 80, 30);

 Color[] data = new Color[80*30];
 for(int i=0; i < data.Length; ++i) data[i] = Color.Chocolate;
 rect.SetData(data);

 Vector2 coor = new Vector2(10, 20);
 spriteBatch.Draw(rect, coor, Color.White);
10
votes

I've just made something very simple which you can call from your Draw method. You can create a rectangle of any dimensions at ease:

private static Texture2D rect;

private void DrawRectangle(Rectangle coords, Color color)
{
    if(rect == null)
    {
        rect = new Texture2D(ScreenManager.GraphicsDevice, 1, 1);
        rect.SetData(new[] { Color.White });
    }
    spriteBatch.Draw(rect, coords, color);
}

Usage:

DrawRectangle(new Rectangle((int)playerPos.X, (int)playerPos.Y, 5, 5), Color.Fuchsia);