C# – Drawing lines in C# with XNA


There is a similar question System.Drawing in XNA, but this may be a clearer question and thus one easier to answer.

We're trying to draw lines on the screen in C#. We are using the XNA library. This code

    void DrawLine2 (Vector2 point1, Vector2 point2)
        System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.Green, 1);
        Point p1 = new Point((int)point1.X, (int)point1.Y), p2 = new Point((int)point2.X, (int) point2.Y);
        Graphics.DrawLine (pen, p1, p2);

gives the compile-time error that Graphics does not exist.

Perhaps I should be using something in XNA to draw the line rather than in System — but if so I am not sure what. XNA has a Spritebatch drawing function, but AFAIK you give it a sprite and a center (and a rotation), rather than 2 points.

Best Solution

Try this handy extensions method,

public static void DrawLine(this SpriteBatch spriteBatch, Vector2 begin, Vector2 end, Color color, int width = 1)
    Rectangle r = new Rectangle((int)begin.X, (int)begin.Y, (int)(end - begin).Length()+width, width);
    Vector2 v = Vector2.Normalize(begin - end);
    float angle = (float)Math.Acos(Vector2.Dot(v, -Vector2.UnitX));
    if (begin.Y > end.Y) angle = MathHelper.TwoPi - angle;
    spriteBatch.Draw(1X1 PIXEL TEXTURE, r, null, color, angle, Vector2.Zero, SpriteEffects.None, 0);
Related Question