Click here to Skip to main content
15,885,984 members
Articles / Desktop Programming / MFC
Article

A custom drawing application based on the .NET Panel class

Rate me:
Please Sign up or sign in to vote.
1.58/5 (25 votes)
6 May 20053 min read 62.5K   1K   22   4
Creation of a custom drawing application based on the .NET Panel class.

Introduction

This article explains the creation of a custom drawing application based on the .NET Panel class.

Background

A Panel is a .NET class which resides in the namespace System.Windows.Forms which can be used to draw/render several custom shapes. It is similar to a canvas/paint area in the Microsoft Paint (MS Paint) application. This can be used to draw several custom shapes using a Graphics object.

In order to effectively use the .NET Panel object, one must implement the method protected override void OnPaint(PaintEventArgs e). This method provides a handle to the Graphics object which in turn can be used to draw/render several shapes using methods like FillEllipse(...), FillRectangle(...) etc.

Sample Image - GDI_DrawingPanel.jpg

Using the Quick Draw Code

In this article, there are several classes used in order to hold several shapes in memory. The following table explains this...

Class NameDescription
ShapeInfoHolds the shape information like shape, color and rectangle object. The rectangle object holds the co-ordinates of the rectangle like top, left, right and bottom.
ShapeInfoCollectionThis class holds a collection of ShapeInfo objects.
DrawingPanelThis is the core class of the application. This class inherits from System.Windows.Forms.Panel.
MainFormThis class handles the form events and fits in all the various parts of this application.

Shape Information - The ShapeInfo class

The code for the class ShapeInfo is shown below...

C#
/// <SUMMARY>
/// Summary description for ShapeInfo.
/// </SUMMARY>
/// <SUMMARY>
/// ShapeInfo - Holds the shape information
///   like shape, color and rectangle object.
/// </SUMMARY>
[Serializable]
public class ShapeInfo
{
    /// <SUMMARY>
    /// Holds the rectangle object.
    /// </SUMMARY>
    private Rectangle _rectangle;

    /// <SUMMARY>
    /// Holds the color object.
    /// </SUMMARY>
    private Color _color;

    /// <SUMMARY>
    /// Holds the shape type.
    /// </SUMMARY>
    private int _shapeType = 0;

    public ShapeInfo()
    {
        // Nothing to do.
    }

    public ShapeInfo(Rectangle rectangle, Color color, int shapeType)
    {
        this._rectangle = rectangle;
        this._color = color;
        this._shapeType = shapeType;
    }

    public Rectangle ShapeRectangle
    {
        get
        {
            return this._rectangle;
        }

        set
        {
            this._rectangle = value;
        }
    }

    public Color ShapeColor
    {
        get
        {
            return this._color;
        }

        set
        {
            this._color = value;
        }
    }

    public int Shape
    {
        get
        {
            return this._shapeType;
        }

        set
        {
            this._shapeType = value;
        }
    }
}

The ShapeInfo class has three main properties:

  • The ShapeRectangle property is used to hold the positional information of the shape. This shall be used to position a particular shape on the Panel/Canvas.
  • The ShapeColor property is used to hold the color related information of the shape. This shall be used to render a particular shape with the specified color on the Panel/Canvas.
  • The Shape property is used to hold the type of the shape. This can be either a 0, 1 or 2 which corresponds to a circle, rectangle, or a square. This shall be used to determine a particular shape.

Painting on the Custom Panel - The DrawingPanel class

This class inherits from the class System.Windows.Forms.Panel. This is used to write custom painting code. The method OnPaint(PaintEventArgs e) needs to be overridden to provide the custom drawing information for the Panel.

C#
/// <SUMMARY>
/// This method provides the drawing board for the graphics object.
/// </SUMMARY>
/// <PARAM name="e"></PARAM>
protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint (e);
    SolidBrush solid = null;
    // Retrieve the Ghaphics context.
    Graphics g = e.Graphics;

    ShapeInfo shapeInfo = null;

    for(int count = 0; count < _shapeColl.Count; count++)
    {
        shapeInfo = (ShapeInfo) _shapeColl[count];

        if (shapeInfo != null)
        {
            // Get the panel info object.
            solid = new SolidBrush(shapeInfo.ShapeColor);

            switch(shapeInfo.Shape)
            {
                case CIRCLE:
                    g.FillEllipse(solid, shapeInfo.ShapeRectangle);
                    break;

                case RECTANGLE:
                    g.FillRectangle(solid, shapeInfo.ShapeRectangle);
                    break;

                case SQUARE:
                    g.FillRectangle(solid,
                       shapeInfo.ShapeRectangle.X ,
                       shapeInfo.ShapeRectangle.Y,
                       shapeInfo.ShapeRectangle.Width,
                       shapeInfo.ShapeRectangle.Width);
                    break;
            }
        }
    }
}

Let us walkthrough this code step-by-step...

  1. First override the method OnPaint(PaintEventArgs e).
  2. Retrieve the Graphics object using the PaintEventArgs argument.
  3. Use the Graphics object reference to invoke methods like FillEllipse and FillRectangle.

This would render the desired shape on the Panel/Canvas and a repainting would occur.

Putting all the bits together...

Once the shapes are determined, the shape information collection is passed to the drawingPanel and the drawingPanel is invalidated.. This shall allow the shape to be rendered on the screen.

C#
private void mouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
    if (_mouseDownFlag && !_mouseUpFlag )
    {
        _mouseUpFlag = false;
        this._shapeInfo.ShapeRectangle
            = new Rectangle(_startX, _startY, (e.X - _startX), (e.Y - _startY));

        drawingPanel.AddToShapeCollection(this._shapeInfo);
        drawingPanel.Invalidate(this._shapeInfo.ShapeRectangle);
    }
}

Take aways...

You have seen how a Panel class can be used in order to draw/render several kinds of shapes on the Panel/Canvas. Note that you would need to call the Invalidate method on the drawingPanel class.

Notice how the binary serialization is done in the code in order to save the images into a file and again restore them back.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect AT&T Wi-Fi Services
United States United States
Naveen has done his Masters (M.S.) in Computer science, has started his career programming the mainframes and now has more than a decade of programming, development and design experience. Naveen has a sharp eye and keen observation skills. Naveen has worked for several companies and strived hard to build large scale business applications and bringing better solutions to the table.
Quite recently Naveen has built a fairly complex integration platform for a large bank. His hobbies include training, mentoring and research. Naveen spends his free time visiting National Parks nationwide.

Naveen has developed the BizTalk Control Center (BCC)
http://biztalkcontrolcenter.codeplex.com

Comments and Discussions

 
GeneralMy vote of 1 Pin
unreal58128-Apr-10 4:12
unreal58128-Apr-10 4:12 
QuestionReally? Pin
Iurii Okhmat8-Jan-10 8:10
Iurii Okhmat8-Jan-10 8:10 
GeneralAttached project is not working properly.,. Pin
Srinath Gopinath6-Jan-10 19:54
Srinath Gopinath6-Jan-10 19:54 
GeneralMy vote of 1 Pin
Mogyi5-Jan-09 2:27
Mogyi5-Jan-09 2:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.