Draw Rectangle in MonoGame

Evorlor picture Evorlor · Apr 26, 2014 · Viewed 16.3k times · Source

How do you draw shapes, such as Rectangles and Circles, in MonoGame without having to save the a predrawn shape in the Content folder?

DrawRectangle() and DrawEllipse() are for Windows Form and do not work in OpenGL, which is what I am using.

Answer

aybe picture aybe · Apr 26, 2014

EDIT

You can learn basic things for MonoGame with tutorials I've put on GitHub : https://github.com/aybe/MonoGameSamples


Use 3D primitives and a 2D projection

Here's a simple example with explanations

I define a 10x10 rectangle and set the world matrix to make it look like a 2D projection :

Note : the BasicEffect is what draws your primitive

protected override void LoadContent()
{
    _vertexPositionColors = new[]
    {
        new VertexPositionColor(new Vector3(0, 0, 1), Color.White),
        new VertexPositionColor(new Vector3(10, 0, 1), Color.White),
        new VertexPositionColor(new Vector3(10, 10, 1), Color.White),
        new VertexPositionColor(new Vector3(0, 10, 1), Color.White)
    };
    _basicEffect = new BasicEffect(GraphicsDevice);
    _basicEffect.World = Matrix.CreateOrthographicOffCenter(
        0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);
}

Then I draw the whole thing :D

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    EffectTechnique effectTechnique = _basicEffect.Techniques[0];
    EffectPassCollection effectPassCollection = effectTechnique.Passes;
    foreach (EffectPass pass in effectPassCollection)
    {
        pass.Apply();
        GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineStrip, _vertexPositionColors, 0, 4);
    }
    base.Draw(gameTime);
}

There you have your rectangle !

enter image description here

Now this is just the tip the of the iceberg,

Or as mentioned in one of the posts above you could use a shader that does it instead ...

I needed to draw a Superellipse a while ago and ended up sketching this shader :

Drawing a SuperEllipse in HLSL

As you can see in the post a Superellipse not only draws ellipse but also other shapes and maybe even circles (I did not test) so you might be interested in it.

Ultimately you will want some class/methods to hide all these details so you just have to invoke something like DrawCircle().

Tip : by posting @ https://gamedev.stackexchange.com/ you will likely get more answers for Monogame-related questions

:D