# Draw lines with arrowheads in C#

If <vx, vy> is a vector between two points, then <-vy, vx> and <vy, -vx> are perpendicular vectors of the same length. If you add and subtract these vectors from the original one, you get new vectors that make a 45 degree angle with the original one. You can use those vectors to make arrowheads and fletchings (tails) for arrows.

The DrawArrowhead method shown in the following code draws a pair of vectors at a 45 degree angle from a vector.

```// Draw an arrowhead at the given point
// in the normalized direction <nx, ny>.
private void DrawArrowhead(Graphics gr, Pen pen,
PointF p, float nx, float ny, float length)
{
float ax = length * (-ny - nx);
float ay = length * (nx - ny);
PointF[] points =
{
new PointF(p.X + ax, p.Y + ay),
p,
new PointF(p.X - ay, p.Y + ax)
};
gr.DrawLines(pen, points);
}```

The following DrawArrow method uses the DrawArrowhead method to draw arrow heads and tails.

```// Draw arrow heads or tails for the
// segment from p1 to p2.
private void DrawArrow(Graphics gr, Pen pen, PointF p1, PointF p2,
float length, EndpointStyle style1, EndpointStyle style2)
{
// Draw the shaft.
gr.DrawLine(pen, p1, p2);

// Find the arrow shaft unit vector.
float vx = p2.X - p1.X;
float vy = p2.Y - p1.Y;
float dist = (float)Math.Sqrt(vx * vx + vy * vy);
vx /= dist;
vy /= dist;

// Draw the start.
{
DrawArrowhead(gr, pen, p1, -vx, -vy, length);
}
else if (style1 == EndpointStyle.Fletching)
{
DrawArrowhead(gr, pen, p1, vx, vy, length);
}

// Draw the end.
{
DrawArrowhead(gr, pen, p2, vx, vy, length);
}
else if (style2 == EndpointStyle.Fletching)
{
DrawArrowhead(gr, pen, p2, -vx, -vy, length);
}
}```

The DrawArrow method draws a line with arrow heads and/or fletchings on the ends. It draws the line and then finds a vector of length 1 in the direction of the line. It call the DrawArrowhead method to draw arrowheads and fletchings appropriately.

This entry was posted in algorithms, geometry, graphics, mathematics and tagged , , , , , , , , , , , . Bookmark the permalink.

### 4 Responses to Draw lines with arrowheads in C#

1. Richard Moss says:

You have unencoded characters, making the first sentence difficult to read.

“If is a vector between two points, then <-v2, v1> and are a perpendicular vectors of the same length”

Looking at the page source shows:

“If is a vector between two points, then <-v2, v1> and are a perpendicular vectors of the same length.”

Regards;
Richard Moss

2. Rod Stephens says:

Doh! Sorry about that. The blogging tool really didn’t like those characters. I think I’ve got it fixed now. Thanks for pointing this out.

3. Yuri says:

Thanks, simple and great code.

This site uses Akismet to reduce spam. Learn how your comment data is processed.