Lines can be drawn in many ways in C#. Here we will try to draw a line using the Graphics.DrawLine method.
Graphics.DrawLine takes a pen to draw the line. So it boils down to the pen to get various styles of lines.
Lets try a simple solid one.
Create a pen. Here again to create a pen we need a Brush. Lets keep it really a simple pen. So we create a simple SolidBrush now.
Brush aSolidBrush = new SolidBrush(Color.Black); //Creates a black solid brush for the pen
Simple isn’t it ??
Pen aSolidPen = new Pen(aSolidBrush); //Assigns the SolidBrush to the Pen
Graphics.DrawLine(aSolidPen, new Point(0, 10), new Point(100, 10)); //Draws a solid horizontal line
Lets play with the different styles of lines now.
Different styles of lines, as said earlier depends on different styles of Pens (which depends on Brushes). So how do we change the style of a pen ??? Answers are many,
Using a Line Pattern
This denotes whether the line is a dotted one or dashed one or dot dashed one or etc. Use the DashStyle property of the pen to change the patter of the line.
aSolidPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash; //Gives you a dashed line
There are a few more styles available in the System.Drawing.Drawing2D.DashStyle enum
aSolidPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; //Gives you a dotted line
Using a DashPattern
This is similar to the first one but here you can control the space and width of the each dot / dash in the line. To manipulate them use the DashPattern property of the pen.
aBorderPen.DashPattern = new float []{ 1, 1 }; //Gives you a dotted line (rather a dashed line with width 1px) and the space bettwen the consecutive dot is 1px
aBorderPen.DashPattern = new float []{ 2, 3 }; //Gives you a dashed line with 2px width for the dashes and 3px width between the dashes
Using a GradientBrush
You can even play with the brushes to get different style lines (as Pens are inturn dependent of Brushes). Use a LinearGradientBrush to get gradient lines.
Brush aGradientBrush = new LinearGradientBrush(new Point(0, 0), new Point(20, 0), Color.Black, Color.Gray); //Gives you a gradinet brush with black and gray colors. This will be a vertical gradient as the second point changes in the x axis
Pen aGradientPen = new Pen(aGradientBrush); //Assigns the GradientBrush to the Pen
Graphics.DrawLine(aGradientPen, new Point(0, 10), new Point(100, 10)); //Draws a horizontal line which is Gradiently Filled
These are some of the ways to draw weird lines in C#. If you have your own style, draw it here.