Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw Rectangle in XNA using SpriteBatch

Tags:

c#

draw

xna

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!

like image 682
user700996 Avatar asked Apr 22 '11 02:04

user700996


People also ask

What is source rectangle XNA?

The source rectangle defines the area of the texture that will be displayed. So if you have a 40x40 texture, and your rectangle is (0, 0, 20, 20), only the top left corner of the texture will be displayed. If you specify null for the rectangle, you will draw the entire texture.


1 Answers

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();
}
like image 155
Andrew Russell Avatar answered Oct 10 '22 04:10

Andrew Russell