MonoGame - Texture2D and Drawing Sprites
By Stephen Armstrong // February 1, 2020
An introduction to drawing 2D graphics.
The following C# code will show you how to display 2D graphics in a MonoGame project.
Texture2D are images that can be used as sprites in 2D games. In this tutorial we will briefly explain them and then demonstrate how to draw them to the screen.
In this tutorial (and in future tutorials) we will be using good ol’ Alex from RPGMaker 2000 as an example.
Download this image and add it to your MonoGame project using the Content Pipeline.
Note the magenta color. By default, MonoGame uses magenta for transparency. The exact value of this color is HTML #FF00FF and rgb(255,0,255).
Setting up
For this tutorial you need to create a Texture2D and a Vector2 in Game1:
// The Texture2D of the charaset.
Texture2D charaset;
// The position to draw the charaset.
Vector2 position;
Now go to LoadContent() and add the following code.
// Load the charaset.
charaset = Content.Load<Texture2D\>("charaset");
// Set the draw position.
position = new Vector2(100, 100);
The texture and its position are now set up.
Drawing the Texture
Go to the Draw() and add the following code:
// Draw the charaset to the position.
spriteBatch.Draw(charaset, position, Color.White);
If you run the code, you’ll see the following:
Texture2D Properties
The following table shows ways to get the size of the Texture2D.
Name | Type | Description |
---|---|---|
.Bounds | Rectangle | The size of the Texture2D |
.Height | int | The height of the Texture2D |
.Width | int | The width of the Texture2D |
These properties can be useful for layout and collision detection, use the following code to test them with the current Texture2D.
// Display the bounds, height, and width of the Texture2D.
System.Console.WriteLine("Bounds: {0}", charaset.Bounds);
System.Console.WriteLine("Height: {0}", charaset.Height);
System.Console.WriteLine("Width: {0}", charaset.Width);
If you run this code you will see the following in the Output.
Further reading
How to Change Color and Transparency: https://www.industrian.net/tutorials/colors-and-transparency/
How to Use Sprite Sheets: https://www.industrian.net/tutorials/using-sprite-sheets/