Click here to Skip to main content
Licence Public Domain
First Posted 1 Feb 2009
Views 35,076
Downloads 1,043
Bookmarked 29 times

CCanvas - A Reusable Class to Draw a Simple Graph

By | 26 Feb 2009 | Article
A reusable class for drawing a simple graph

Introduction

Actually I am a little nervous to introduce this article. This is my first experience with MFC. Here I make a reusable class that is capable of drawing objects such as rectangle, ellipse, circle, and line by using GDI Device Context programming. The objects are selectable, moveable, and resizable. It is named CCanvas. I hope it will be useful for you. You can use it in your project that requires a simple graph editor.

Using the Code

Class Methods

Here are some public methods:

  • bool loadFile(char *fileName);

    Loads a file.

  • bool saveFile(char *fileName);

    Saves a file.

  • void set(CPoint ptStart, CPoint ptEnd);

    Retrieves start and end position when mouse is dragged.

  • set(int tool);

    Sets active tool: draw rectangle, draw ellipse, draw circle, or erase.

  • int update(CDC *dc);

    Updates window.

  • void store();

    Stores object into memory.

  • void drawGrid(CDC *dc, HWND hwnd, int gridsizeX, int gridsizeY)();

    Draw grids within specified size.

  • void setSnapToGrid(bool setting, int gridsizeX, int gridsizeY);

    Set snap-to-grid option within specified grid size.

How It Works

It works by handling these three important messages:

  • WM_LBUTTONDOWN - Start drawing, remember the origin position of the mouse pointer
  • WM_MOUSEMOVE - Here it tracks mouse movement, remember its current position
  • WM_LBUTTONUP - Finish drawing, store the newly created object into memory

How to Use

Let's say you have an SDI project, named Demo.

  • Add the file "canvas.h" to your DemoView.h:

    #include "canvas.h"
  • Add these variables to your DemoView.h:

    private:
        CCanvas m_canvas;
        CPoint m_ptStart;
        CPoint m_ptEnd;
  • Add these window messages to your DemoView.cpp:

    BEGIN_MESSAGE_MAP(CDemoView, CView)
        //{{AFX_MSG_MAP(CDemoView)
        ON_WM_MOUSEMOVE()
        ON_WM_LBUTTONUP()
        ON_WM_LBUTTONDOWN()
        //}}AFX_MSG_MAP
    END_MESSAGE_MAP()
  • Add these codes to your DemoView.cpp to handle those window messages:

    void CDemoView::OnDraw(CDC* dc)
    {
        CNiceDoc* pDoc = GetDocument();
        ASSERT_VALID(pDoc);
    
        m_canvas.update(dc);
    }
    
    BOOL CDemoView::PreCreateWindow(CREATESTRUCT& cs)
    {
        m_canvas.setSnapToGrid(true, 10, 10);
        return CView::PreCreateWindow(cs);
    }
    
    void CDemoView::OnMouseMove(UINT nFlags, CPoint point)
    {
        CView::OnMouseMove(nFlags, point);
    
        // Update end point while mouse is moving
        if (GetCapture() == this){
    	m_ptEnd = point;
    	Invalidate();
    	m_canvas.set(m_ptStart, m_ptEnd);
        }
    }
    
    void CDemoView::OnLButtonDown(UINT nFlags, CPoint point)
    {
        CView::OnLButtonDown(nFlags, point);
    
        // Get start point for drawing
        m_ptStart = m_ptEnd = point;SetCapture();
        m_canvas.set(m_ptStart, m_ptEnd);
    }
    
    void CDemoView::OnLButtonUp(UINT nFlags, CPoint point)
    {
        CView::OnLButtonUp(nFlags, point);
    
        // Get end point for drawing
        if (GetCapture() == this)
        {
            ReleaseCapture();
            m_ptEnd = point;
            Invalidate();
            m_canvas.store();
        }
    }

Loading and Saving Documents

Function members for loading and saving documents are called in class CDemoDoc that exists in file DemoDoc.h and DemoDoc.cpp. It is a pretty long explanation. You can see it yourself in the demo source code. Basically it is simply a "how you deal with CDocument."

Flickering Issue - Double Buffering

To get rid of the flickering issue, we can use the double buffering method. Look here. Follow the steps and you will see the flickering issue go away. The demo project attached with this article uses this method.

Points of Interest

This is my first MFC project and I am still improving it. I plan to add more features like:

  • More object shapes
  • Rotation
  • Ordering (backward and forward)
  • Select and move multiple objects
  • Coloring
  • Etc.

1st Update

I have fixed major bugs when creating vertical line. You cannot do anything to vertical line, it seems to be frozen. This is because of the incomplete mathematics equation I use in the code. I also added two new features: setSnapToGrid and drawGrid. I adapted code from Johan Rosengren for the drawGrid function. Don't worry, the rest is still original and kept to be as simple as it could be. Besides those things, now when you do resizing, the mouse cursor will change based on the resizing direction. The source is also converted to VC++ 2005. I think VC++6.0 has been abandoned.

History

  • 31st January, 2009: Initial version
  • 25th February, 2009: 1st update 

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication

About the Author

auralius manurung

Other
Gyeongsang National University, South Korea
Indonesia Indonesia

Member

from Indonesia with love... Smile | :)

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 3 Pinmemberliujichao3:41 3 Nov '10  
QuestionDoes CCanvas function on CScrollView ? Pinmembermesajflaviu6:27 28 Jun '10  
AnswerRe: Does CCanvas function on CScrollView ? Pinmemberauralius manurung16:08 2 Jul '10  
GeneralGreat Job Pinmemberxox_c0bra_xox18:41 25 Jul '09  
GeneralRe: Great Job Pinmemberauralius7:19 26 Jul '09  
Questionwhat is DRAWCLI from microsoft? PinmemberSouthmountain19:03 2 May '09  
AnswerRe: what is DRAWCLI from microsoft? Pinmemberauralius14:54 15 May '09  
QuestionCan it support PrintPreview? Pinmembermaplewang18:30 27 Feb '09  
AnswerRe: Can it support PrintPreview? Pinmemberauralius18:45 1 Mar '09  
GeneralDrawCLI Pinmemberprcarp5:49 27 Feb '09  
GeneralRe: DrawCLI Pinmemberauralius18:44 1 Mar '09  
GeneralMy vote is 5 Pinmembertyjiang22:38 26 Feb '09  
GeneralRe: My vote is 5 Pinmemberauralius0:17 27 Feb '09  
GeneralHello Auralius PinmemberJerry Evans1:25 4 Feb '09  
GeneralRe: Hello Auralius Pinmemberauralius16:14 4 Feb '09  
GeneralMy vote of 2 PinmemberCountry Man5:33 3 Feb '09  
GeneralRe: My vote of 2 Pinmembermerano7:18 3 Feb '09  
GeneralRe: My vote of 2 Pinmemberauralius11:52 3 Feb '09  
GeneralRe: My vote of 2 PinmemberTim Craig17:31 26 Feb '09  
GeneralRe: My vote of 2 Pinmemberauralius0:31 27 Feb '09  
GeneralRe: My vote of 2 Pinmembermaplewang16:29 24 May '09  
GeneralMy vote of 2 PinmemberTomas Rapkauskas0:24 3 Feb '09  
GeneralRe: My vote of 2 Pinmemberemilio_grv4:43 3 Feb '09  
GeneralRe: My vote of 2 Pinmemberauralius12:32 3 Feb '09  
GeneralRe: My vote of 2 PinmemberTim Craig17:32 26 Feb '09  

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.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 26 Feb 2009
Article Copyright 2009 by auralius manurung
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid