|
Language: VB.NET Expertise: Intermediate
Mar 30, 2002
Dashed lines with custom caps
You can set properties of the Pen object to create custom lines. For example, you can use the DashStyle enumerated property to draw dashed lines using a predefined pattern, and you can even create custom dash patterns by assigning an array of Single values to the DashPattern property. The StartCap and EndCap properties can take an enumerated value and let you change the shape of the starting and ending point of the line so that you can easily create arrows or other common shapes. Here's a code that creates several lines with different styles:
' This statement assumes that you have imported the System.Drawing namespace
' This code should run inside a Windows Form class
Dim gr As Graphics = Me.CreateGraphics
Dim p1 As New Pen(Color.Black, 3)
p1.DashStyle = Drawing.Drawing2D.DashStyle.Dash
gr.DrawLine(p1, 10, 10, 200, 10)
p1.DashStyle = Drawing.Drawing2D.DashStyle.DashDot
gr.DrawLine(p1, 10, 30, 200, 30)
p1.DashStyle = Drawing.Drawing2D.DashStyle.DashDotDot
gr.DrawLine(p1, 10, 50, 200, 50)
p1.DashStyle = Drawing.Drawing2D.DashStyle.Dot
gr.DrawLine(p1, 10, 70, 200, 70)
' Create a custom dash pattern.
Dim sngArray() As Single = {4, 4, 8, 4, 12, 4}
p1.DashPattern = sngArray
gr.DrawLine(p1, 10, 90, 200, 90)
' Display pens with nondefault caps.
Dim p2 As New Pen(Color.Black, 8)
p2.StartCap = Drawing.Drawing2D.LineCap.DiamondAnchor
p2.EndCap = Drawing.Drawing2D.LineCap.ArrowAnchor
gr.DrawLine(p2, 280, 30, 500, 30)
p2.StartCap = Drawing.Drawing2D.LineCap.RoundAnchor
p2.EndCap = Drawing.Drawing2D.LineCap.Round
gr.DrawLine(p2, 280, 70, 500, 70)
' Destroy custom Pen objects.
p1.Dispose()
p2.Dispose()
gr.Dispose()
Francesco Balena
|