Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » C# Language » The Basics of Drawing Graphics onto Windows Forms

The Basics of Drawing Graphics onto Windows Forms

This article gives you an explanation of the use of the GDI+ library and how the .NET base classes can enhance graphics.

Page Views : 24619
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction:

GDI+ consists of the set of .NET base classes that are available to control custom drawing on the screen. These classes arrange for the appropriate instructions to be sent to the graphics device drivers to ensure the correct output is placed on the screen. GDI provides a level of abstraction, hiding the differences between different video cards. You simply call on the Windows API function to do the specific task, and internally the GDI figures out how to get the client's particular video card to do whatever it is you want when they run your particular piece of code.

Not only this, but the client has several display devices - for example - monitors and printers - GDI achieves the task of making the printer look the same onscreen as far as the application is concerned. If the client wants to print something instead of displaying it, your application will simply inform the system that the output device is the printer and then call the same API functions in exactly the same way. As you can see, the device-context (DC) object is a very powerful mechanism. Having said that, we can also use this layer of abstraction to draw onto a Windows Form. This paper will therefore begin with an example of a  basic Windows Forms development in order to demonstrate how to draw graphics onto a Windows Form, or a control on that form. The focus of this article will be on graphics.

The Form object is used to represent any Window in your application. When creating a main window, you must follow two mandatory steps:

  1. Derive a new custom class from System.Windows.Forms.Form
  2. Configure the application's Main() method to call System.Windows.Forms.Application.Run(), passing an instance of your new Form derived as a class argument.

Here is an example:
 
C# File: MyForm.cs

using System;

using System.Windows.Forms;

public class MyForm : System.Windows.Forms.Form

{

    public MyForm()

    {

        Text = "No Graphics";

    }

    public static void Main()

    {

        Application.Run(new MyForm());

    }
}

To compile:

C:\Windows\Microsoft.NET\Framework\v2.050727>csc /target:winexe MyForm.cs

So now we have a blank form. So what do we do to learn how to use graphics? If you use Visual Studio 2005 you probably know that the .NET Framework 2.0  supports partial classes. With Visual Studio 2005, a Windows Form is completely defined with a single C# source file. The code generated by the IDE was separated from your code by using regions, therefore taking advantage of partial classes.

By default, each form named Form111 corresponds to two files; Form111.cs which contains your code and Form111.Designer.cs, which contains the code generated by the IDE. The code, however, is usually generated by dragging and dropping controls. One of the simplest uses for the System.Drawing namespace is specifying the location of the controls in a Windows Forms application. More to the point, user-defined types are often referred to as structures.

To draw lines and shapes you must follow these steps:

  1. Create a Graphics object by calling System.Windows.Forms.Control.CreateGraphics method. The Graphics object contains the  Windows DC you need to draw with. The device control created is associated with the display device, and also with the Window.
  2. Create a Pen object
  3. Call a member of the Graphics class to draw on the control using the Pen

Here is an example of a Form with a line drawn at a 60 degree angle from the upper-most left hand corner:

//File: DrawLine.cs
 

using System;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

public class MainForm : System.Windows.Forms.Form

{

    private System.ComponentModel.Container components;

 

    public MainForm()

    {

        InitializeComponent();

        CenterToScreen();

        SetStyle(ControlStyles.ResizeRedraw, true); 

    } 

 

    //  Clean up any resources being used.

 

    protected override void Dispose(bool disposing)

    {

        if (disposing)

        {

            if (components != null)

            {

                components.Dispose();

            }

        }

        base.Dispose(disposing);

    }

    #region Windows Form Designer generated code

 

    private void InitializeComponent()

    {

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

        this.ClientSize = new System.Drawing.Size(292, 273);

        this.Text = "Fun with graphics";

        this.Resize += new System.EventHandler(this.Form1_Resize);

        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 

    }

    #endregion 

 

    [STAThread]

    static void Main()

    {

        Application.Run(new MainForm());

    }

 

    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

    {

        //create a graphics object from the form

        Graphics g = this.CreateGraphics();

        // create  a  pen object with which to draw

        Pen p = new Pen(Color.Red, 7);  // draw the line 

        // call a member of the graphics class

        g.DrawLine(p, 1, 1, 100, 100);

    }

    private void Form1_Resize(object sender, System.EventArgs e)

    {

        // Invalidate();  See ctor!

    }

}
 
TO COMPILE:

csc.exe /target:winexe DrawLine.cs
 
Typically, you specify the Pen class color and width in pixels with the constructor. The code above draws a 7-pixel wide red line from the upper-left corner (1,1,) to a point near the middle of the form (100, 100).  Note the following code that draws a pie shape:
                 
File:// DrawPie.cs
                    

using System;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

 

 

public class MainForm : System.Windows.Forms.Form

{

    private System.ComponentModel.Container components;

 

    public MainForm()

    { 

        InitializeComponent();

        CenterToScreen();

        SetStyle(ControlStyles.ResizeRedraw, true); 

    }

    protected override void Dispose(bool disposing)

    {

        if (disposing)

        {

            if (components != null)

            {

                components.Dispose();

            }

        }

        base.Dispose(disposing);

    }
 

    #region Windows Form Designer generated code

    //

    private void InitializeComponent()

    {

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

        this.ClientSize = new System.Drawing.Size(292, 273);

        this.Text = "Fun with graphics";

        this.Resize += new System.EventHandler(this.Form1_Resize);

        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 

    }

    #endregion
 

    [STAThread]

    static void Main()

    {

        Application.Run(new MainForm());

    }

 

    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

    { 

        //create a graphics object from the form

        Graphics g = this.CreateGraphics();

        Pen p = new Pen(Color.Blue, 3);

        g.DrawPie(p, 1, 1, 100, 100, -30, 60);

    }

    private void Form1_Resize(object sender, System.EventArgs e)

    {

    }

}

To compile:

csc.exe /target:winexe DrawPie.cs

A structure, or "struct", is a cut-down class that does almost everything a class does, except support inheritance and finalizers. A structure is a composite of other types that make easier to work with related data. The simplest example is  System.Drawing.Point, which contain X and Y integer properties that define the horizontal and vertical coordinates of a point.

The Point structure simplifies working with coordinates by providing constructors and members as follows:

// Requires reference to System.Drawing

// Create point

System.Drawing.Point p = new System.Drawing.Point(20, 20);

// move point diagonally

p.Offset(-1, -1)

Console.WriteLine("Point X {0}, Y {1}", p.X, p.Y.);

So as the coordinates of a point define its location, this process also specifies a control's location. Just create a new Point structure by specifying the coordinates relative to the upper-left corner of the form, and use the Point to set the control's Location property.

Graphics.DrawLines, Graphics.DrawPolygons, and Graphics.DrawRectangles accept arrays as parameters to help you draw more complex shapes:

Here is an example of a polygon, but with its contents filled. Notice the code responsible for filling the shape:

DrawPolygonAndFill.cs
                    

using System;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data; 

 

public class MainForm : System.Windows.Forms.Form

{

    private System.ComponentModel.Container components;

 

    public MainForm()

    {

        InitializeComponent();

        CenterToScreen();

        SetStyle(ControlStyles.ResizeRedraw, true);

    }

    protected override void Dispose(bool disposing)

    {

        if (disposing)

        {

            if (components != null)

            {

                components.Dispose();

            }

        }

        base.Dispose(disposing);

    } 

 

    #region Windows Form Designer generated code

    private void InitializeComponent()

    {

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

        this.ClientSize = new System.Drawing.Size(292, 273);

        this.Text = "Fun with graphics";

        this.Resize += new System.EventHandler(this.Form1_Resize);

        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 

    }

    #endregion

 

    [STAThread]

    static void Main()

    {

        Application.Run(new MainForm());

    }

    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

    {

 

        //create a graphics object from the form

        Graphics g = this.CreateGraphics();

        Brush b = new SolidBrush(Color.Maroon);

        Point[] points = new Point[]
        
{
            new Point(10, 10),

            new Point(10, 100),

            new Point(50, 65),

            new Point(100, 100),

            new Point(85, 40)};   // Notice the braces, as used in structures

            g.FillPolygon(b, points);

        }

    private void Form1_Resize(object sender, System.EventArgs e)

    {

    }

}  

Customizing Pens:

The color and size of a pen is specified in the Pen constructor, so you can manipulate the pattern and the endcaps. The endcaps are the end of the line, and you can use them to create arrows and other special effects. While pens by default draw straight lines, their properties can be set to one of these values: DashStyle.Dash, DashStyle.DashDot, DashStyle.DashDotDot, DashStyle.Dot, or DashStyle.Solid. Consider this final example:

UsePen.cs
                   

using System;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

public class MainForm : System.Windows.Forms.Form

{

    private System.ComponentModel.Container components;

 

    public MainForm()

    { 

        InitializeComponent();

        CenterToScreen();

        SetStyle(ControlStyles.ResizeRedraw, true); 

    } 

 

    //  Clean up any resources being used.

 

    protected override void Dispose(bool disposing)

    {

        if (disposing)

        {

            if (components != null)

            {

                components.Dispose();

            }

        }

        base.Dispose(disposing);

    } 

 

    #region Windows Form Designer generated code

 

    private void InitializeComponent()

    {

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

        this.ClientSize = new System.Drawing.Size(292, 273);

        this.Text = "Learning graphics";

        this.Resize += new System.EventHandler(this.Form1_Resize);

        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 

    }

    #endregion 

 

    [STAThread]

    static void Main()

    {

        Application.Run(new MainForm());

    }

 

    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

    { 

        //create a graphics object from the form

        Graphics g = this.CreateGraphics();

        // create a Pen object

        Pen p = new Pen(Color.Red, 10);

        p.StartCap = LineCap.ArrowAnchor;

        p.EndCap = LineCap.DiamondAnchor;

        g.DrawLine(p, 50, 25, 400, 25);

 

        p.StartCap = LineCap.SquareAnchor;

        p.EndCap = LineCap.Triangle;

        g.DrawLine(p, 50, 50, 400, 50);

 

        p.StartCap = LineCap.Flat;

        p.EndCap = LineCap.Round;

        g.DrawLine(p, 50, 75, 400, 75);

 

        p.StartCap = LineCap.RoundAnchor;

        p.EndCap = LineCap.Square;

        g.DrawLine(p, 50, 100, 400, 100);

    }

    private void Form1_Resize(object sender, System.EventArgs e)

    {

        // Invalidate();  See ctor!

    }

}
 
The basics underlying principles in this paper indicate the location and size of points so that they for a line or a shape. This should the new developer to understand that these principles can be expanded upon to specify the size and location of controls that are dragged and dropped onto a Windows Form. For instance, if we were to start Visual Studio 2005 and begin a Forms application, we could set that Form background color to white. The designer file and the source file that comprise the application would both reflect that property: the setting of the property would cause the IDE to generate the code in the Form.Designer.cs file. Well, that all for now. 

DrawLine.cs
            

using System;

using System.Drawing;

using System.Drawing.Drawing2D;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data; 

 

public class MainForm : System.Windows.Forms.Form

{ 

    private System.ComponentModel.Container components; 

    public MainForm()

    { 

        InitializeComponent();

        CenterToScreen();

        SetStyle(ControlStyles.ResizeRedraw, true); 

    } 

 

    //  Clean up any resources being used.

 

    protected override void Dispose(bool disposing)

    {

        if (disposing)

        {

            if (components != null)

            {

                components.Dispose();

            }

        }

        base.Dispose(disposing);

    }
 

    #region Windows Form Designer generated code

 

    private void InitializeComponent()

    {

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

        this.ClientSize = new System.Drawing.Size(292, 273);

        this.Text = "Learning graphics";

        this.Resize += new System.EventHandler(this.Form1_Resize);

        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 

    }

    #endregion 

 

    [STAThread]

    static void Main()

    {

        Application.Run(new MainForm());

    }

 

    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)

    { 

        //create a graphics object from the form

        Graphics g = this.CreateGraphics();

 

        // create  a  pen object with which to draw

        Pen p = new Pen(Color.Red, 7);

 

        // draw the line  

        g.DrawLine(p, 1, 1, 100, 100);

    }
 

    private void Form1_Resize(object sender, System.EventArgs e)

    {

        // Invalidate();  See ctor!

    }

}

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dave
I have been studying the .NET Framework and the C# language for around a year. My first experience with programming was learning MS DOS DEBUG. I am about at an intermediate level with the CLR and the JVM. I am self taught and in need of tutorials to clarify the structure of C#, Vb, and other language programs.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.