Wednesday, May 18, 2011

Code: How to draw a Line that follows a path in WPF

I couldn't find a code snippet online that did exactly this, so I thought I'd share.  The following code draws a line on a path that ends up being 3 straight lines:


//line looks somethine like:
//
//    |
//    \
//     \
//      |
Point p1 = new Point(GetAdjustXPositionForIntrusion(model.LengthInInches, item.LocationInInches), canvasHeight - padding - 2);
Point p2 = new Point(p1.X, p1.Y - intrusionHeight);
Point p3 = new Point(textCanvasLeft + 4, intrusionTextBottom + intrusionHeight);
Point p4 = new Point(p3.X, intrusionTextBottom);
 
List<PathSegment> segments = new List<PathSegment>();
segments.Add(new LineSegment(p2, true));
segments.Add(new LineSegment(p3, true));
segments.Add(new LineSegment(p4, true));
 
PathFigure pf = new PathFigure(p1, segments, false);
                    
PathGeometry pg = new PathGeometry();
pg.Figures.Add(pf);
 
Path p = new Path();
p.Data = pg;
p.Stroke = GetBrushForIntrusionType(item.IntrusionType);
p.StrokeThickness = 1;
canvas.Children.Add(p)