Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw Rectangle with XNA

I am working on game. I want to highlight a spot on the screen when something happens.

I created a class to do this for me, and found a bit of code to draw the rectangle:

static private Texture2D CreateRectangle(int width, int height, Color colori) {     Texture2D rectangleTexture = new Texture2D(game.GraphicsDevice, width, height, 1, TextureUsage.None,     SurfaceFormat.Color);// create the rectangle texture, ,but it will have no color! lets fix that     Color[] color = new Color[width * height];//set the color to the amount of pixels in the textures     for (int i = 0; i < color.Length; i++)//loop through all the colors setting them to whatever values we want     {         color[i] = colori;     }     rectangleTexture.SetData(color);//set the color data on the texture     return rectangleTexture;//return the texture } 

The problem is that the code above is called every update, (60 times a second), and it was not written with optimization in mind. It needs to be extremely fast (the code above freezes the game, which has only skeleton code right now).

Any suggestions?

Note: Any new code would be great (WireFrame/Fill are both fine). I would like to be able to specify color.

like image 571
Ben Avatar asked May 08 '10 02:05

Ben


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

The SafeArea demo on the XNA Creators Club site has code to do specifically that.

You don't have to create the Texture every frame, just in LoadContent. A very stripped down version of the code from that demo:

public class RectangleOverlay : DrawableGameComponent {     SpriteBatch spriteBatch;     Texture2D dummyTexture;     Rectangle dummyRectangle;     Color Colori;      public RectangleOverlay(Rectangle rect, Color colori, Game game)         : base(game)     {         // Choose a high number, so we will draw on top of other components.         DrawOrder = 1000;         dummyRectangle = rect;         Colori = colori;     }      protected override void LoadContent()     {         spriteBatch = new SpriteBatch(GraphicsDevice);         dummyTexture = new Texture2D(GraphicsDevice, 1, 1);         dummyTexture.SetData(new Color[] { Color.White });     }      public override void Draw(GameTime gameTime)     {         spriteBatch.Begin();         spriteBatch.Draw(dummyTexture, dummyRectangle, Colori);         spriteBatch.End();     } } 
like image 91
Bob Avatar answered Oct 04 '22 10:10

Bob