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 arrow heads and fletchings.

The DrawArrowhead method shown in the following code draws a pair of vectors at a 45 degree angle from a vector. The DrawArrow method described next uses it to draw arrow heads and tails.

// 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 DrawArrow method shown in the following code draws a line with arrow heads or fletchings on the ends. It draws the line and then finds a vector of length 1 in the direction of the line. It then uses the DrawArrowhead method to draw arrowheads and fletchings appropriately.

// 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.
if (style1 == EndpointStyle.ArrowHead)
{
DrawArrowhead(gr, pen, p1, -vx, -vy, length);
}
else if (style1 == EndpointStyle.Fletching)
{
DrawArrowhead(gr, pen, p1, vx, vy, length);
}

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

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

  • 9/1/2010 8:49 AM Richard Moss wrote:
    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
    Reply to this
    1. 9/1/2010 9:12 AM Rod Stephens wrote:
      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.
      Reply to this
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.