Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Newbie  »  Chart Success: GDI+ Graphics at work. Part 1  »  Drawing
 »  Home  »  Windows Development  »  Graphics  »  Chart Success: GDI+ Graphics at work. Part 1  »  Drawing
Chart Success: GDI+ Graphics at work. Part 1
by Ged Mead | Published  03/06/2005 | .NET Newbie Graphics | Rating:
Drawing

Draw The Chart
   Armed with our figures, we may now draw our pie chart.  The OnPaint continues with:

   '  Create variables to hold the changing values of Angles
   Dim StartAngle As Single = 0
   Dim SweepAngle As Single = 0

   And we cycle through the data for each company, drawing its segment in the chosen color.

  For Each gd As GraphData In Companies
    SweepAngle = 360 * gd.amount / TotalCount
    g.FillPie(New SolidBrush(gd.Clr), rect, StartAngle, 
      SweepAngle)
    StartAngle += SweepAngle
  Next

The breakdown of the above code block goes like this:
1. Select the next company in the arraylist
2. Calculate how many of the 360 degrees it owns
3. Draw the Pie:

  •  Filling the segment with this company’s color,
  •  Containing the pie inside the Rectangle
  •  Starting the segment at the correct point on the ellipse
  •  Continuing for the number of degrees calculated for this company

4. Move the start position for the next segment by adding the number of degrees just used for the current segment.

Improve the Chart
   We’ve already improved the look of the chart by setting the SmoothingMode to HighQuality, but I also quite like to finish off the display by putting edge lines round each of the segments.

   This is refreshingly easy to do.   Insert this additional code line just below the FillPie method in the code snippet above:

  g.DrawPie(New Pen(Color.Brown), rect, StartAngle, SweepAngle)

   You can alter the impact of the lines by changing the line color as you prefer.

Creating The Chart Key
    The Heading
    The text for the Chart’s Key is created using another Graphics method – DrawString.  

    We have already seen both the Pen and the Brush objects in action in the code above; the Brush to fill the segments, the Pen to draw the exterior lines.    When it comes to drawing text with the DrawString method, you might expect to use a Pen object for this.   By another of those quirks of the graphics class, you actually need a Brush to draw the text string, not a Pen.

  You will recall that we created the Brush for the pie segments on the fly in this code line:


 g.FillPie(New SolidBrush(gd.Clr), rect, StartAngle, SweepAngle)

  We could do something similar with our text drawing code, but it would make it harder to read and analyze.   So we will create the text brush separately.  For the same reason, we will create the Font for the text separately too.  

'  Create a Brush to draw the text
  Dim TextBrsh As Brush = New SolidBrush(Color.Black)
'  Create a Font object instance for text display
  Dim TextFont As New Font("Arial", 12, FontStyle.Bold)

    Maybe it’s just me, but I have sometimes found setting the font arguments to be a bit tricky.   Intellisense isn’t always your best friend in this particular situation, so take care to enter the arguments you really want, in the correct order.

     Writing (drawing) the  heading of the Key comes next:

 g.DrawString("Chart Key", TextFont, TextBrsh, 310, 100)  

      The two values at the end of the above code line are the X and Y positions of the start of the text (i.e left and top positions on the Form).

Bullets and Company Info
   
    Because we are now going to create several lines of text that we want to keep aligned vertically, the X position (pixel count from the left of the form) will stay the same.    However, the Y position, counting from the top of the form will of course change as we move down the form displaying line after line.   To keep track of this Y position we will use an Integer variable.

  Dim pxFromTop As Integer = 135

   I have placed the first line of company info 35 pixels below the Heading, 135 pixels below the top of the form.  

   Now we can again enumerate through the arraylist and use the information in there to create the detail of the chart key.   You will see from the commenting included how we have achieved this.   
 

  For Each gd As GraphData In Companies
   '  Draw bullet
   g.FillEllipse(New SolidBrush(gd.Clr), 310, pxFromTop, 15, 15)
   '  Draw line round bullet.
   g.DrawEllipse(New Pen(Color.Black), 310, pxFromTop, 15, 15)
   '  Draw the text - color coded
   g.DrawString(gd.Description & " (" & gd.Amount & ")", TextFont,   
       TextBrsh, 360, pxFromTop)
   '  Increase gap from Top for next line
    pxFromTop += 30 
  Next

 The only code which might need additional explanation are the values:

310 in the first two lines is the X Position of the circular bullet
15, 15  in the first two lines represent the width and height of the ellipse. 
  (Making their values equal will of course result in a circle)
360 in the third line is the X Position where we want the Company Name to begin.

   I think we have covered variations of all the other settings in previous code snippets.

 Dispose After Use
    All that is left to do is the housekeeping - disposing of any disposable graphics objects that we specifically created as we were drawing.  

     TextBrsh.Dispose()
   TextFont.Dispose()

   Notice that we don’t try to dispose of any of the Brushes and Pens we created on the fly in code and also that we don’t dispose of the Graphics Object in this particular example.   This is an area we will look at in more detail in future articles, as we need to.


All Done!
     I have taken a lot of space to describe what is in fact not very much code.   Hopefully, the extra detail and explanation will help you to see how you can create your own versions of this kind of pie chart and key.
 

     There is a sample solution attached to this article if you would like to see it in action.   However, there is no substitute for making your own mistakes as the best way to learn, so I do recommend that you try entering the code yourself in a new project and come back for the explanations if things don’t go quite as you expect.

      The final version of the chart and key should look something like this:

 

Comments    Submit Comment

Comment #1  (Posted by an unknown user on 03/13/2005)
Rating
The subject you have picked is one of the most interesting ones in programming. But sure enough, that may just be my opinion. When an interesting subject comes with explanations that are detailed but still very readable, then this means that the author has a great talent for writing and it shows immense responsibility and patience with beginning programmers. And that’s exactly what your article has achieved.
 
Comment #2  (Posted by an unknown user on 03/16/2005)
Rating
Very nice, Ged.

A small suggestion for part II: when would you use GDI+ vs. DirectX?
 
Comment #3  (Posted by Ged Mead on 03/22/2005)
Rating
Thanks for the comments. Part 2 is out now .... but I think it'll be a while before I get round to DirectX!
 
Comment #4  (Posted by an unknown user on 06/12/2005)
Rating
Hi Ged,
Nice and the way u explained is excellent .
The explanation is in steps and easy to understand and for me it the best methord to understand .
Good work i dont have word to appriciate u but excellent job.
From
Mohd Sufian
IT Specialist
Eastern Polymer Group
Thailand
 
Comment #5  (Posted by Dave on 10/03/2005)
Rating
Explained quite well! However I have a persistence problem that you mention in your article. I am drawing inside a picture box. My drawing code is in its own function which I call from the Paint() method. When the form first opens my drawing flashes up quite briefly and then disappears. It reappears and remains whenever I resize the window. How do I get it to come up without telling it to refresh which puts it in an endless loop?
 
Comment #6  (Posted by an unknown user on 04/05/2006)
Rating
Great explanation.I would like to know how to integrate database data with GDI.
 
Comment #7  (Posted by Ronan on 04/13/2006)
Rating
Hi i have read these tutorials and am looking your help.
I am trying to develop a pie chart interface in Visual Studio 2003 for a PDA (Smart Device Application) and tried your code. however it is not compatible as it does not recognise the drawPie and FillPie commands, etc. Do you have an example i could use to help me for this?
Thank you, Ronan
 
Comment #8  (Posted by an unknown user on 08/09/2006)
Rating
Excellent article. I have learnt a lot of GDI+ Stuff from it.
 
Comment #9  (Posted by an unknown user on 10/19/2006)
Rating
Very Useful article. Prakash Bajaj
 
Comment #10  (Posted by an unknown user on 12/22/2006)
Rating
really useful
 
Comment #11  (Posted by an unknown user on 12/29/2006)
Rating
no corners cut, all is clear
 
Comment #12  (Posted by an unknown user on 07/09/2007)
Rating
thank you
Very simple
detailed explanation
 
Comment #13  (Posted by an unknown user on 07/22/2007)
Rating
best for beginner's. language is just perfect
 
Comment #14  (Posted by neelabh on 07/22/2007)
Rating
Language is clear nd decription is best for beginner
 
Comment #15  (Posted by an unknown user on 10/01/2007)
Rating
Easy to follow tutorial. Picked up the main points straight away.
 
Comment #16  (Posted by an unknown user on 12/28/2007)
Rating
I have been searching for a good graphics article to get me started...with this one I found what I was looking for...GREAT JOB. Now I need to found out how to do vertical text.
 
Comment #17  (Posted by an unknown user on 02/05/2008)
Rating
Free, good, patient advice. A rare commodity and precious to beginners.
 
Comment #18  (Posted by an unknown user on 02/06/2008)
Rating
thanks for giving such a good article to start GDI+ from scratch.
 
Comment #19  (Posted by an unknown user on 02/20/2008)
Rating
good one
 
Sponsored Links