Now i’ve been looking around and a question a few seem to have is how to generate a filled rectangle in XNA. Well the simple truth is that XNA doesnt provide these methods directly to you But it does allow you to get or set the color data of a Texture. So that is exactly what were going to do.Texture2D’s can be created whenever you want without a content manage unlike the Model class does. So first create a Textured2D variable wherever you want preferably above the constructor so that you can immediatly can go to it without searching through tons of lines.
So you should have something like this:
Texture2D myTexture;
public Game1()
{
...
}
Now with that done lets move onto creating a method that will return a valid Texture2D
private Texture2D CreateRectangle(int width,int height)
{
Texture2D rectangleTexture = new Texture2D(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] = new Color(0, 0, 0,255);
}
rectangleTexture.SetData(color);//set the color data on the texture
return rectangleTexture;//return the texture
}
Now go to your LoadContent Method if you don’t know what that is then look for this line of code
protected override void LoadContent()
so inside that method( or inside the { and } ) add the following
myTexture = CreateRectangle(640, 480);//give it a width of 640 and a height of 480
And there we go, now when the the Game loads the Content it will create our lovely filled rectangle. Simple right?
Now to make sure the texture is in fact there you will have to draw it so lets go down to our Draw method( or protected override void Draw(GameTime gameTime) ) and below GraphicsDevice.Clear(Color.CornflowerBlue); add the following
spriteBatch.Begin();
spriteBatch.Draw(myTexture, Vector2.Zero, Color.White);
spriteBatch.End();
now run the game and you should see something like this
the final code is of course below
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace DrawRectangle
{
///
/// This is the main type for your game
///
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D rectangle;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = “Content”;
}
public Texture2D CreateRectangle(int width, int height)
{
Texture2D rectangleTexture = new Texture2D(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
for (int i = 0; i < color.Length; i++)//loop through all the colors setting them to whatever values we want
{
color[i] = new Color(0, 0, 0,255);
}
rectangleTexture.SetData(color);//set the color data on the texture
return rectangleTexture;
}
///
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
///
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
///
/// LoadContent will be called once per game and is the place to load
/// all of your content.
///
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
rectangle = CreateRectangle(640, 480);
// TODO: use this.Content to load your game content here
}
///
/// UnloadContent will be called once per game and is the place to unload
/// all content.
///
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
///
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
///
///
Provides a snapshot of timing values. protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
///
/// This is called when the game should draw itself.
///
///
Provides a snapshot of timing values. protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(rectangle, Vector2.Zero, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
4 Comments
Comments RSS TrackBack Identifier URI


Why not just make a texture with a single white pixel and use the SpriteBatch.Draw(Texture2D texture, Rectangle destinationRectangle, Color color) method? That way, the texture can be reused for any color you need by simply changing the color parameter. It’s a waste of resources to create a new, sized Texture2D for every single Rectangle color & size combination you will need.
I agree with you JeBuS .I am fully of aware of that lil bit of info. BUT The aim of this tut was not for just for displaying a simple rectangle on screen, but to show HOW to edit the pixels of an Texture2D. to achieve the colored effects you want AT Run time. I think i am not explaining myself good enough here. Let me give an example of a possible use for this.
Lets say you wanted to do your very own Image Editing app..using XNA, just for the heck of it.
You know how to create a filled rectangle, either through A White Blank texture or my lovely lil tut here. Now you have no idea at all how to edit those Pixels to achieve certain effects.Indeed you COULD use HLSL and achieve many of those effects in a quite speedy fasten. But lets just say for my sake of the argument that you had no idea how to code in HLSL or even use it in XNA. But lets say your coming from a GDI+ background and know how to do many of the effects already,such as Gaussian Blur,Emboss. The same concepts apply easy enough to apply to port over to XNA, as long as you know how to apply a pixel ‘s color or loop through a texture’s pixels or whatever.
That probably didnt make TOO MUCH sense because at the moment i am really tired.
But just know that yes one of the main points was about displaying a filled rectangle, but also about how to set a pixel on a texture, existing or not. And its always good to know how to do things another possible way!.
I probably shouldve posted more pics of possible outcomes if you got creative, so as soon as i can i’ll post some up. And you just gave me the most wonderful idea JeBuS so thanks!.
EDIT:
JeBuS if you think you can write an article or tutorial about anything else let me know! I’ll gladly post it up here with your name as the author of it.
EDIT2:
If anyone wants a new tut about something please let me know,I’ll be more than glad to take a crack at it.
I definitely didn’t get that you were purposely showing how to use the GetData and SetData. If that’s the case, nevermind.
Don’t worry about it, in fact i thought it was rather good that you brought that point up, I am sure it cleared some air about this tutorial too.