[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Draw lines with arrowheads in C#

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

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.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.