Custom line caps in WPF


The attached project contains a custom element (FrameworkElement-derived), which allows definition of line paths (straight lines, Bezier curves, etc.) with custom-defined line caps. The following graphic contains two lines: a straight line with an arrow and filled rectangle at either end, and an irregular path with a circle and and arrow.

(Note that this is sample code, devoid of most error checks, not necessarily optimized for performance and possibly missing some functionality not directly related to the line cap display, e.g. layout override).

Xaml used to create this graphic is as follows. It is using the custom CappedLine element, whose source code is contained in the attached project. Line caps (BeginCap and EndCap) are defined as geometry properties. The line itself is defined through the CappedLine property of type PathGeometry. CappedLine places the end caps in such a way that their 0,0 point coincides with either the beginning or the end of the line itself. It also rotates the caps so that they are oriented along the tangents at line ends.

 

        <Canvas Height="350" Width="525">

            <loc:CappedLine BeginCap="M0,0 L6,-6 L6,6 z" EndCap="M0,-3 L0,3 L6,3 L6,-3 z" Stroke="Red" StrokeThickness="1" Canvas.Left="40" Canvas.Top="60">

                <loc:CappedLine.LinePath>

                    <PathGeometry Figures="M0,0 L120,120" />

                </loc:CappedLine.LinePath>

            </loc:CappedLine>

 

            <loc:CappedLine EndCap="M0,0 L6,-6 L6,6 z" Stroke="Red" StrokeThickness="1" Canvas.Left="40" Canvas.Top="200" RenderTransformOrigin="0.5,0.5">

                <loc:CappedLine.BeginCap>

                    <EllipseGeometry Center="0,0" RadiusX="6" RadiusY="6" />

                </loc:CappedLine.BeginCap>

                <loc:CappedLine.LinePath>

                    <PathGeometry Figures="M0,0 C1,1 10.5,75.5 48.5,66.5 86.5,57.5 53.5,3.5000146 105.5,16.500091 157.5,29.500166 164.5,87.500505 164.5,87.500505" />

                </loc:CappedLine.LinePath>

                <loc:CappedLine.RenderTransform>

                    <RotateTransform Angle="{Binding Value,ElementName=slider}" />

                </loc:CappedLine.RenderTransform>

            </loc:CappedLine>

 

        </Canvas>

 

LineCaps.zip

Comments (0)

Skip to main content