Blog

Adding Line Caps with XAML

By Ken Getz | January 17, 2013

line cap options

The Line shape represents a straight line that connects two points. Set four >properties to define the location of the line: X1 and Y1 set the starting point, and X2 and Y2 set the ending point.

When drawing Line shapes (and also Polyline shapes) you have the option of controlling how the starting and ending edges of the lines appear. You can set the StrokeStartLineCap and StrokeEndLineCap properties to control this behavior.

NOTE: The StrokeStartLineCap and StrokeEndLineCap properties haveno effect on closed shapes, such as Rectangle, Ellipse, and Polygon.

You can select from the following choices when setting the StrokeStartLineCap and StrokeEndLineCap properties:

  • Flat (the default value): The line ends immediately at its starting/final value.
  • Round: The ends with extra space, half the thickness of the line, with a rounded cap.
  • Square: The ends with extra space, half the thickness of the line, with a squared-off cap.
  • Triangle: The ends with extra space, half the thickness of the line, with a triangle cap.

TIP: The only difference between the Flat and Square line caps is that the Square line cap adds extra length to the line equivalent to half the thickness of the line.

If you add a value for the StrokeStartLineCap and/or the StrokeEndLineCap property, you will extend the length of the line by half the stroke width on the corresponding end(s) of the line. The Figure below shows four examples, one for eachof the line cap options. In each example, the figure shows a 20-pixel-wide line, and a 10-pixel-wide line. Look carefully, and you can see the additional lengthadded because of the line cap.

TIP: You can add a line cap at one end of the line or the other, or both. The StrokeStartLineCap property refers to the end corresponding to the X1 and Y1 coordinates for the line.

Each example in the Figure below (from the sample page, LineCaps.xaml) uses markup like the following (each example changes the line cap and stroke thickness properties):

<Line X1="20" Y1="30"
X2="400" Y2="30"
StrokeStartLineCap="Flat"
StrokeEndLineCap="Flat"
Stroke="Black"
StrokeThickness="20" />

ldn-expertkgetzThis post is an excerpt from the online courseware for our Windows 8 Using XAML: Bindings, Shapes, and Animation course written by expert Ken Getz.



Ken Getz

Ken Getz is a featured instructor for several of our Visual Studio courses. He is a Visual Basic and Visual C# expert and has been recognized multiple times as a Microsoft MVP. Ken is a seasoned instructor, successful consultant, and the author or co-author of several best-selling books. He is a frequent speaker at technical conferences like Tech-Ed, VSLive, and DevConnections and he has written for several of the industry's most-respected publications including Visual Studio Magazine, CoDe Magazine, and MSDN Magazine.


This blog entry was originally posted January 17, 2013 by Ken Getz