How can i Draw Lines in Monogame?

1.8k views Asked by At

I just started learning monogame a couple of days ago and I was wondering how I can draw a line from a Start Vector2 and an End Vector2 with a specific line thickness?

Should I use a one pixel image to draw it onto the screen and then use a Bresenham's line algorithm to find there positions, or is there a more optimized and less complicated method to do this using monogames built in functions?

2

There are 2 answers

0
lrpe On

One way is to create a Texture2D with a width that is the distance between the two Vector2s and a height that is the desired width. Then you apply a rotation to the texture when you draw it.

Here is an example (as a SpriteBatch extension method):

public static void DrawLineBetween(
    this SpriteBatch spriteBatch,
    Vector2 startPos,
    Vector2 endPos,
    int thickness,
    Color color)
{
    // Create a texture as wide as the distance between two points and as high as
    // the desired thickness of the line.
    var distance = (int)Vector2.Distance(startPos, endPos);
    var texture = new Texture2D(spriteBatch.GraphicsDevice, distance, thickness);

    // Fill texture with given color.
    var data = new Color[distance * thickness];
    for (int i = 0; i < data.Length; i++)
    {
        data[i] = color;
    }
    texture.SetData(data);

    // Rotate about the beginning middle of the line.
    var rotation = (float)Math.Atan2(endPos.Y - startPos.Y, endPos.X - startPos.X);
    var origin = new Vector2(0, thickness / 2);

    spriteBatch.Draw(
        texture,
        startPos,
        null,
        Color.White,
        rotation,
        origin,
        1.0f,
        SpriteEffects.None,
        1.0f);
}

Example of use:

var startPos = new Vector2(0, 0);
var endPos = new Vector2(800, 480);
_spriteBatch.DrawLineBetween(startPos, endPos, 12, Color.White);

How it looks:

enter image description here

It's not a perfect solution. You'll want to modify it if you want to draw connected lines with different angles without any visible seams. Also not sure about the performance.

0
Frecklefoot On

I use a library I found. It draws a number of 2D primitives, like lines, boxes, etc. Really easy to use. Called "C3.MonoGame.Primitives2D", it can be found here: https://github.com/z2oh/C3.MonoGame.Primitives2D

Here's a screenshot of a demo I wrote using many of its methods:

C3.Monogame.Primitives2D

It's just one file of around 500 lines. If you don't like Git or using libraries, you can just copy & paste it into your project.