Open WinForms - Open Source Windows Forms and Controls

{} DailyCoding.com - Tips and tricks - C#, ASP.NET
 Subscribe in a reader

 
Home    Controls    Articles    Contact
  Drawing line patterns in GDI+
 
 
Post comments    Need help?

Introduction

GDI+ has made the windows graphics programming really easy. You can easily draw and control the graphical interface of you application. This section will explain how can you draw pattern lines in GDI+.

To do anything in GDI+, you always need the object of Graphics class. Most of the GDI+ related code in called in Paint event of ant windows controls. You can attach handler of this event.
this.Paint += new PaintEventHandler(this_Paint);
   
private void this_Paint(object sender, PaintEventArgs e)
{
  // drawing code here.
}

A simple line could be drawn using Graphics.DrawLine function, however you need object on Pen to draw a line.
Pen pen = new Pen(Color.Green, 2.0F);
e.Graphics.DrawRectangle(pen, 10, 10, 200, 100);
e.Graphics.DrawLine(pen, 20, 20, 200, 20);
e.Graphics.DrawLine(pen, 20, 30, 200, 30);
e.Graphics.DrawLine(pen, 20, 40, 200, 40);
pen.Dispose();

Solid Line C# GDI+

Patterned lines

You can externally specify the pattern of the line using Pen.DashStyle. There are some build in patterns available in .net. (Dash, Dot, DashDot, DashDotDot)
Pen pen = new Pen(Color.Black, 2.0F);
pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;

e.Graphics.DrawRectangle(pen, 10, 10, 200, 100);
e.Graphics.DrawLine(pen, 20, 20, 200, 20);
e.Graphics.DrawLine(pen, 20, 30, 200, 30);
e.Graphics.DrawLine(pen, 20, 40, 200, 40);
pen.Dispose();

Solid Line C# GDI+

Setting Custom Patterns

If you want to create you own custom pattern of the line, then you can use the Pen.DashPattern to set you own custom pattern.
Pen pen = new Pen(Color.Black, 2.0F);
pen.DashPattern = new float[] { 4, 2, 13, 4, 2, 3 };

e.Graphics.DrawRectangle(pen, 10, 10, 200, 100);
e.Graphics.DrawLine(pen, 20, 20, 200, 20);
e.Graphics.DrawLine(pen, 20, 30, 200, 30);
e.Graphics.DrawLine(pen, 20, 40, 200, 40);
pen.Dispose();

Solid Line C# GDI+
 
Post comments    Need help?
Sponsors
 
  Tags: GDI+ Drawing, Pattern,

Facing issue while using? contact sa@openwinforms.com
 
 

Contact Site Admin: sa@openwinforms.com