使用XNA在C#中绘制线条

时间:2013-05-06 17:19:03

标签: c# xna

有一个类似的问题System.Drawing in XNA,但这可能是一个更清晰的问题,因此更容易回答。

我们正试图在C#中在屏幕上画线。我们正在使用XNA库。这段代码

    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);
    }

给出了Graphics不存在的编译时错误。

也许我应该在XNA中使用某些东西来绘制线而不是在系统中 - 但如果是这样,我不确定是什么。 XNA有一个Spritebatch绘图功能,但AFAIK你给它一个精灵和一个中心(和一个旋转),而不是2点。

2 个答案:

答案 0 :(得分:8)

试试这个方便的扩展方法,

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);
}

答案 1 :(得分:3)

Spritebatch可以用来绘制一条线,正如Beanish所说,你可以简单地制作一个像素精灵并在两点之间扩展它。

这是一个很棒的库,用于在XNA中绘制2D基元,它使用绘制线条以及弧形等其他对象。我广泛使用它:

http://sourceforge.net/projects/primitives2d/

相关问题