Click here to Skip to main content
Click here to Skip to main content

Extensions to DrawTools

, 7 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
DrawTools library extended to include Layers, Zoom, Pan, Rotation

Updated 10/4/2011

Draw Tools Redux Image


Alex Fr provided an excellent set of drawing tools in his DrawTools article and these tools serve as a basis for this article, which expands on the original toolset in the following ways:

  1. In addition to the basic Rectangle, Ellipse, Line and Scribble tools, this version adds PolyLine, Filled Ellipse, Filled Rectangle, Text and Image tools
  2. Multiple drawing Layers
  3. Zooming
  4. Panning
  5. Rotation

In this article, I will describe how Layers were implemented, as well as the Text and Image tools.


See the original DrawTools article for details on how the basic application is built, class structure, etc.

It is also assumed that the reader has a working understanding of GDI+ fundamentals, including Matrices. For an excellent introduction to GDI+, see

Implementing Layers

Adding Layers to the application involved adding two classes, Layer and Layers, where Layer defines a single Layer and Layers defines the collection of Layers in an ArrayList.

Each Layer exposes the following properties:

 private string _name;
 private bool _isDirty;
 private bool _visible;
 private bool _active;
 private GraphicsList _graphicsList;

Note that the Layer contains the GraphicsList - this is the key to the whole thing - each Layer contains its own list of drawing objects instead of DrawArea. DrawArea is modified to declare a Layers collection instead of a GraphicsList collection:

 // Define the Layers collection
 private Layers _layers; 

When DrawArea is initialized, the Layers are initialized by creating the first Layer and setting it Active and Visible:

 public DrawArea()
 // create list of Layers, with one default active visible layer
 _layers = new Layers();
 _panning = false;
 _panX = 0;
 _panY = 0;
 // This call is required by the Windows.Forms Form Designer.

In the Layers class, the CreateNewLayer() method actually creates the new Layer:

 /// <summary>
 /// Create a new layer at the head of the layers list and set it 
 /// to Active and Visible.
 /// </summary>
 /// <param name="theName">The name to assign to the new layer</param>
 public void CreateNewLayer(string theName)
 // Deactivate the currently active Layer
 if(layerList.Count > 0)
 ((Layer)layerList[ActiveLayerIndex]).IsActive = false;
 // Create new Layer, set it visible and active
 Layer l = new Layer();
 l.IsVisible = true;
 l.IsActive = true;
 l.LayerName = theName;
 // Initialize empty GraphicsList for future objects
 l.Graphics = new GraphicsList();
 // Add to Layers collection

Note that any one or all Layers can be visible at the same time, but only one Layer may be active at any time.

You can control the Layers in the sample application by clicking on the Current Layer: name at the bottom of the application window - Click on the name ("Default") to open the Layers dialog:

From this dialog, you can Add new Layers, change the names of the Layer(s), and change the Layer(s) visibility and which Layer is Active. The "New Layer" column is checked whenever you click the "Add Layer" button. To delete Layer(s), simply check the "Deleted" column and close the dialog with the "Close" button. Remember only one Layer may be active at any one time. You will be reminded of this if you attempt to have more than one Layer active. Also note the Active Layer must be Visible.

When the application runs, each object that is drawn is added to the GraphicsList maintained by the active Layer. Note this relationship is preserved through saving and re-opening a drawing file.

Layers come in very handy when you want to draw "on top of" another image. For example, the image at the top of this article contains two layers. The following image shows the same picture with the Background Layer turned off:

Here is the same drawing with the Drawing Layer invisible and the Background Layer visible:

Objects on Layers which are visible but not active cannot be selected, moved, deleted, etc.

Each drawing object is added to the correct Layer by the AddNewObject() method in the ToolObject class:

protected void AddNewObject(DrawArea drawArea, DrawObject o)
     int al = drawArea.TheLayers.ActiveLayerIndex;
     o.Selected = true;
   o.Dirty = true;
     drawArea.Capture = true;

Implementing Zooming, Panning, and Rotation

Zooming, Panning, and Rotation are implemented by adding a few variables and some code to the MainForm and DrawArea classes.

Zooming is controlled by buttons on the form, and also by the mouse wheel when Ctrl is held down.

Pan is controlled by the Hand button on the form, and can be cancelled by a right-click.

Rotation is controlled by buttons on the form - note Rotation affects the entire drawing.

Here is an example of all three in use:

Screenshot - DrawToolsRedux-3.png

The heart of this code is the BackTrackMouse() method, which takes the "apparent" mouse position and converts it to a valid point based on the current Zoom level, Pan position, and Rotation:

/// <summary>
 /// Back Track the Mouse to return accurate coordinates regardless of 
 /// zoom or pan effects.
 /// Courtesy of <seealso cref=""/>
 /// </summary>
 /// <param name="p">Point to backtrack</param>
 /// <returns>Backtracked point</returns>
 public Point BackTrackMouse(Point p)
     // Backtrack the mouse...
     Point[] pts = new Point[] { p };
     Matrix mx = new Matrix();
     mx.Translate(-this.ClientSize.Width / 2, -this.ClientSize.Height / 2, 
     mx.Rotate(_rotation, MatrixOrder.Append);
     mx.Translate(this.ClientSize.Width / 2 + _panX, this.ClientSize.Height / 2 + 
			_panY, MatrixOrder.Append);
     mx.Scale(_zoom, _zoom, MatrixOrder.Append);
     return pts[0];

This routine comes from Bob Powell's excellent website. Through the use of the GDI+ Matrix class, the mouse point passed to this method is moved (Translate), Rotated, and Scaled based on the current PanX, PanY, Zoom, and Rotation values. The important thing to remember is that anytime you need to determine where the mouse pointer actually is in your drawing, you must call this method. You will see this method used throughout the program in the DrawArea class as well as others. An example of its usage is shown here:

private void DrawArea_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
     lastPoint = BackTrackMouse(e.Location);
     if (e.Button == MouseButtons.Left)
         tools[(int)activeTool].OnMouseDown(this, e);
     else if (e.Button == MouseButtons.Right)
         if (_panning == true)
             _panning = false;
         ActiveTool = DrawArea.DrawToolType.Pointer;

The current zoom level is controlled by the following simple routine:

private void AdjustZoom(float _amount)
    drawArea.Zoom += _amount;
    if (drawArea.Zoom < .1f)
        drawArea.Zoom = .1f;
    if (drawArea.Zoom > 10)
        drawArea.Zoom = 10f;

Then in the DrawArea.Paint() method, the zoom, pan, and rotation values are used to alter the way the canvas is painted:

private void DrawArea_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    Matrix mx = new Matrix();
    mx.Translate(-this.ClientSize.Width / 2, -this.ClientSize.Height / 2, 
    mx.Rotate(_rotation, MatrixOrder.Append);
    mx.Translate(this.ClientSize.Width / 2 + _panX, this.ClientSize.Height / 2 + 
			_panY, MatrixOrder.Append);
    mx.Scale(_zoom, _zoom, MatrixOrder.Append);
    e.Graphics.Transform = mx;

    SolidBrush brush = new SolidBrush(Color.FromArgb(255, 255, 255));
    // Draw objects on each layer, in succession so we get the correct layering.
    // Only draw layers that are visible
    if (_layers != null)
        int lc = _layers.Count;
        for (int i = 0; i < lc; i++)
            if(_layers[i].IsVisible == true)
                if(_layers[i].Graphics != null)

Update - 8/25/2007 - Individual Object Rotation & Bug Fixes

The primary advancement in this update is the ability to rotate individual objects - when one or more objects are selected, clicking the Rotate tools will rotate those objects instead of the entire drawing surface.

There is one caveat, however - the selection rectangle for the rotated object is not rotated - if someone can help with this, I would greatly appreciate it!

This update also includes several small bug fixes reported by users - thanks to all for reporting!


  • 3/6/2007
    • Original article uploaded to The Code Project
  • 3/6/2007
    • Updated to include more information on zoom/pan/rotation
  • 8/25/2007
    • Updated Individual Object Rotation
  • 9/27/2007
    • Added the missing links to the new source code
  • 12/23/2009
    • Added Tooltip control which appears when mouse is over an object. Tooltip displays the Center coordinates of the object for Rectangle, Ellipse and Image objects. For other objects, Tooltip displays starting and ending coordinates. Text objects do not display Tooltip.
      This was implemented adding the Tooltip control to the ToolPointer class. Each Draw Object fills the TipText property and the MouseMove event in ToolPointer controls when the Tooltip is displayed and removed from the canvas. This implementation is not perfect, as the Tooltip flashes when displayed so is meant as an example of one way information about the object can be displayed.
      Perhaps a better way to do this would be to display information about the object in a separate "Information Window" and then only when the object is selected.
    • See the new source code for details.
  • 6/23/2010
    • Updated project to include object ordering fix that corrects the way objects are stacked when a file is opened
    • Updated project to Visual Studio 2010
    • See the new source code for details
  • 10/4/2011
    • Corrected several issues with Layers and layering


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Mark Miller
Software Developer (Senior)
United States United States
I develop software for a leading healthcare system in Northern Illinois.

Comments and Discussions

QuestionGreat Job!!! Impressive!!!! Thank You.All the best!!! Pinmemberelim.projects1-Oct-14 1:01 
Generalexcellent PinmemberMember 107827952-May-14 17:50 
QuestionImpressive ! PinmemberLurebu31-Mar-14 22:37 
QuestionSpecifies a user-defined custom dash style Pinmembertmp198620-Mar-14 10:14 
QuestionProblem for Layer Export Pinmembermichaelzhu30-Sep-13 14:58 
QuestionAdd drawarea to panel Pinmembernoinhotnn14-Aug-13 18:37 
QuestionSave background image with visuals to a file PinmemberTodd Cherry25-Mar-13 5:15 
AnswerRe: Save background image with visuals to a file Pinmembermeaningoflights4-May-13 19:12 
GeneralMy vote of 5 PinmemberEdo Tzumer27-Jan-13 21:04 
QuestionIs there any WPF version for Drawtools /extensions to Drawtools Pinmemberbmanikandan8610-Oct-12 22:53 
AnswerRe: Is there any WPF version for Drawtools /extensions to Drawtools Pinmembercarazuza31-Oct-12 6:20 
QuestionGroup and ungroup objects Pinmemberbommc200327-Aug-12 17:25 
AnswerRe: Group and ungroup objects PinmemberMember 99979233-May-13 23:24 
QuestionBackground Color and Background Image Pinmemberalexandre.dutra30-May-12 10:57 
AnswerRe: Background Color and Background Image PinmemberMark Miller5-Jun-12 4:58 
GeneralMy vote of 5 Pinmembermanoj kumar choubey20-Feb-12 21:30 
GeneralMy vote of 5 Pinmemberalexandre.dutra9-Jan-12 14:10 
QuestionCan not add DrawTool.dll in toolbox Pinmembersanang4-Jan-12 4:43 
AnswerRe: Can not add DrawTool.dll in toolbox PinmemberMark Miller4-Jan-12 5:29 
GeneralMy vote of 5 Pinmemberalexandre.dutra27-Dec-11 4:33 
Question+5 and fyi: is no longer on-line PinmemberBillWoodruff8-Oct-11 11:25 
GeneralMy vote of 5 PinmemberWooters7-Oct-11 8:46 
GeneralObject moving issue PinmemberMember 28478463-Oct-11 0:03 
Mark, you work very hard and also have added many feature on existing program but still I not prefer your program because of it has problem in object moving. It will be great if we can fix below issue
(1) once after adding any object on the screen it should be in pointed position
(2) If I add any image and trying to move that image, I can move that image but other object are fixed.
GeneralRe: Object moving issue PinmemberMark Miller3-Oct-11 5:14 
QuestionMoving Issue PinmemberMember 28478463-Oct-11 0:01 
QuestionMy vote of 5 PinmemberFilip D'haene30-Sep-11 7:51 
QuestionGetting properties of each created object--help please!!! PinmemberMember 774292523-Jun-11 21:10 
GeneralRotate and Pan Pinmemberkirrukirru15-Jun-11 5:22 
GeneralFilled text with color Pinmemberjani66621-Feb-11 12:36 
GeneralRe: Filled text with color Pinmemberjani66621-Feb-11 13:08 
GeneralRe: Filled text with color PinmemberMark Miller23-Feb-11 6:27 
Generalcopy paste function PinmemberVinaykumar Singh21-Feb-11 3:19 
GeneralRe: copy paste function PinmemberMark Miller23-Feb-11 6:26 
GeneralDocument Icon Pinmemberyehongyehong17-Feb-11 16:32 
Questionhow to draw connector from obj1<--->obj2 PinmemberFahroong.NET10-Nov-10 16:26 
GeneralSmooth polyline. Pinmembertranvantinhpt15-Jul-10 17:37 
GeneralRe: Smooth polyline. PinmemberMark Miller16-Jul-10 4:25 
GeneralRe: Smooth polyline. PinmemberMark Miller16-Jul-10 10:20 
GeneralRe: Smooth polyline. Pinmembertranvantinhpt16-Jul-10 16:17 
GeneralObject order behavior Pinmembersamurai92615-May-10 12:53 
GeneralRe: Object order behavior PinmemberMark Miller18-May-10 8:29 
GeneralRe: Object order behavior PinmemberMark Miller21-May-10 4:54 
GeneralRe: Object order behavior Pinmembersamurai92621-May-10 5:09 
GeneralRe: Object order behavior Pinmembersamurai92611-Jun-10 15:14 
GeneralRe: Object order behavior PinmemberMember 327235318-Jun-10 10:52 
GeneralRe: Object order behavior Pinmembersamurai92619-Jun-10 2:52 
GeneralRe: Object order behavior PinmemberMember 327235319-Jun-10 6:42 
GeneralRe: Object order behavior Pinmembersamurai92620-Jun-10 4:24 
GeneralRe: Object order behavior PinmemberMark Miller23-Jun-10 5:10 
QuestionZoom problem using Mouse Wheel and Zoom To Selected Area PinmemberManuel Salvatori11-May-10 6:19 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150326.1 | Last Updated 7 Oct 2011
Article Copyright 2007 by Mark Miller
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid