Skip to content

Instantly share code, notes, and snippets.

@kenpower
Created October 17, 2012 20:45
Show Gist options
  • Save kenpower/3908061 to your computer and use it in GitHub Desktop.
Save kenpower/3908061 to your computer and use it in GitHub Desktop.
Draw 2D line in XNA using a streched 1x1 sprite
Texture2D t; //base for the
protected override void LoadContent()
{
// create 1x1 texture for line drawing
t = new Texture2D(GraphicsDevice, 1, 1);
t.SetData<Color>(
new Color[] { Color.White });// fill the texture with white
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
DrawLine(spriteBatch, //draw line
new Vector2(100, 100), //start of line
new Vector2(500, 500) //end of line
);
spriteBatch.End();
base.Draw(gameTime);
}
void DrawLine(SpriteBatch sb, Vector2 start, Vector2 end)
{
Vector2 edge = end - start;
// calculate angle to rotate line
float angle =
(float)Math.Atan(edge.Y / edge.X);
if (edge.X < 0)
angle = MathHelper.Pi + angle;
sb.Draw(t,
new Rectangle(// rectangle defines shape of line and position of start of line
(int)start.X,
(int)start.Y,
(int)edge.Length(),
1), //width of line, change this to make thicker line
null,
Color.Red, //colour of line
angle, //angle of line (calulated above)
new Vector2(0, 0), // point in line about which to rotate
SpriteEffects.None,
0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment