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

3D Pie Chart in ASP.NET

, 27 Apr 2003
Rate this:
Please Sign up or sign in to vote.
Discusses the implementation of a 3D pie chart in ASP.NET

Sample Image - image001.jpg

Introduction

I decided to document my little 3D pie chart demonstration and possibly submit it to CodeProject. I must note I have done very little with graphical programming.

It all started when I was contemplating the length of a rounded edge of a pie slice given the radius and the degree of the slice angle. I never did find the formula, but I figure you could take the circumference of the circle as a whole then divide it by eight pieces if the degree was 45 as in the chart above. Hold on, that is the answer!

Anyway, I then started to ask myself how you can programmatically draw a pie chart. That might give my some idea. I found a complex WebChart control off CodeProject by user blong. I also had some simple ASHX code from Jeff Prosise on MSDN, Aug. 2002.

The Graphics method FillPie can draw a pie slice given the mid point, the length and width of the ellipse, starting angle and sweep angle. The mid point is the graphical coordinates where the "device context" will put the middle of the ellipse. Think of it as 0, 0 in an x, y coordinate system where the degrees are as in Figure 2.

I created a VB.NET project to demo the FillPie method, a DrawPieChart example, and a Draw3DPieChart demonstration where this ASP.NET (ASPX page) demo came from. Unfortunately, I don’t have an IIS server accessible to the Internet, but the Windows application can be downloaded here.

The sweep angle is self explanatory, but it threw me off at first. If the start angle was 35 degrees and you wanted a pie slice to go to 90 digress, you would set the sweep to 55 not 90.

To draw the simple pie chart I just created a loop to start at 0 and go to 315 skipping every 45 degrees. Note: I randomly chose brush colors and I didn’t think that 360 being the same as 0 would be a problem until I did the 3D demo.

The 3D test came next. For pie slices less then 180 degrees required that I used a System.Drawing.Drawing2D.HatchBrush with the random color selected for the slice, and drew 10 slices dropping the y coordinate on each FillPie method call to give the illusion of depth.

To draw the displaced pie slice was an added challenge. I forget what the code did without the displaced slice, but to draw the chart in Figure 1, I noted that starting with the pie slice at 180 degrees and wrapping around (0 to 315, see code below), would draw the chart correctly. For simplicity sake, I "painstakingly" kept the degrees under 360.

There it is; pretty simple. I figure if it was not worth the time to design a better, reusable version of the project. What would be the best format? This ASPX as listed below? Use an ASHX file like Jeff’s? What about the legend, chart title? It would take more time and desire then my simple inquiry. Besides, you might as well use the WebChart control stated above. It’s already written!

Assuming I’d take the time to write a reusable chart, here are the steps I’d use for the algorithm. Sort the array or list of elements (test scores, votes. etc.) from greatest number to the smallest. In this demo all degree angles for the slices are 45.

To determine angle degrees per slice I would sum up the elements, take the value of an element divide it by the sum, and then multiply it by 360. Take the simple arbitrary sample data of .NET platform users:

  1. J# Users : 5%
  2. C# Users : 80%
  3. VB.NET Users : 15%

Sorting would result in {80, 15, 5} and starting at 180 degrees, loop through the list. The "C# Users" slice would sweep (80/100*360) or 288 degrees; "VB.NET Users", 54 degrees; and the displaced "J# Users" slice, 18 degrees.

In my demo, I just randomly select colors using RGB values. Known solid colors would make it more desirable to the eye. Another pleasing feature was this:

objGraphics.SmoothingMode = SmoothingMode.AntiAlias;

Compare this to the choppy images created without this line of code. I think that’s it. Hope it is worth something to someone. Maybe this documentation is just for my own purposes when I look at the code years from now.

The chart wouldn’t print straight from Internet Explorer. I wonder if that was because I wasn’t referring (href) the page from an HTML image tag - which did print.

    <%@ Import Namespace="System.Drawing"%>
    <%@ Import Namespace="System.Drawing.Imaging"%>
    <%@ Import Namespace="System.Drawing.Drawing2D" %>
    <script language="C#" runat="server">

    void Page_Load(Object sender, EventArgs e)
    {
        // Since we are outputting a Jpeg, set the ContentType appropriately
        Response.ContentType = "image/jpeg";

        // Create a Bitmap instance that's 468x60, and a
        Graphics instance

        const int width = 300, height = 300;

        Bitmap objBitmap = new Bitmap(width, height);
        Graphics objGraphics = Graphics.FromImage(objBitmap);

        // Create a black background for the border
        objGraphics.FillRectangle(new SolidBrush(Color.White), 0, 0,<BR>        width, height);

        Draw3DPieChart(ref objGraphics);

        // Save the image to a file
        objBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
        
        // clean up...
        objGraphics.Dispose();
         objBitmap.Dispose();
    }  

    // Draws a 3D pie chart where ever slice is 45 degrees in value
    void Draw3DPieChart(ref Graphics objGraphics)
    {
        int iLoop, iLoop2;

        // Create location and size  of ellipse.
        int x  = 50;
        int y  = 20;
        int width  = 200;
        int height = 100;

        // Create start and sweep angles.
        int startAngle = 0;
        int sweepAngle = 45;
        SolidBrush oibjBrush = new SolidBrush(Color.Aqua);

        Random rand = new Random();
        objGraphics.SmoothingMode = SmoothingMode.AntiAlias;

        //Loop through 180 back around to 135 degress so it gets drawn<BR>    // correctly.
        for( iLoop = 0; iLoop <= 315; iLoop += 45)
        {
            startAngle = (iLoop + 180) % 360;
            objBrush.Color = Color.FromArgb(rand.Next(255), rand.Next(255),<BR>                rand.Next(255));

            // On degrees from 0 to 180 draw 10 Hatched brush slices to show<BR>            // depth
            if((startAngle < 135) || (startAngle == 180))
            {
                for(iLoop2 = 0; iLoop2 < 10; iLoop2++)
                    objGraphics.FillPie(new HatchBrush(HatchStyle.Percent50,
                        objBrush.Color), x, 
                        y + iLoop2, width, height, startAngle, sweepAngle);
            }

            // Displace this pie slice from pie.
            if(startAngle == 135)
            {
                // Show Depth
                for(iLoop2 = 0; iLoop2 < 10; iLoop2++)
                    objGraphics.FillPie(new HatchBrush(HatchStyle.Percent50,
                        objBrush.Color), x - 30,
                        y + iLoop2 + 15, width, height, startAngle,<BR>                        sweepAngle);

                objGraphics.FillPie(objBrush, x - 30, y + 15,
                    width, height, startAngle, sweepAngle);
            } 
            else // Draw normally
                objGraphics.FillPie(objBrush, x, y, width,
                    height, startAngle, sweepAngle);
        }
    }
    </script>

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

Share

About the Author

MJDamron
Software Developer
United States United States
I enjoy messing with application development and some Web development technologies. Right now I work in Virginia as a contractor to the government.
 
I am a Microsoft Cert. Professional and I got my 4 year BS degree.
 
See web site for resume and other code samples.

Comments and Discussions

 
QuestionCan we show percentage on top of each slice ? PinmemberPankaj Garg14-Feb-14 11:16 
QuestionHow to See Chart ?? PinmemberOzgur KOC29-Dec-07 5:17 
AnswerRe: How to See Chart ?? PinmemberRajib Ahmed3-Mar-08 6:09 
AnswerRe: How to See Chart ?? Pinmemberharshadptl422-Feb-13 23:07 
QuestionHow to link it to the Database PinmemberSijo Mathew11-Oct-07 2:45 
QuestionBroken link yet again Pinmemberdarksander19-Sep-07 5:14 
GeneralFormula you were searching for PinmemberAnthony Potts26-May-06 7:01 
GeneralTypo Pinmemberpaulanthony13-Feb-06 23:07 
General3D Pie Edit Version with subtitle Pinmemberhockey223-May-05 23:00 
GeneralRe: 3D Pie Edit Version with subtitle PinmemberBelkira3-May-06 0:27 
QuestionQuality? PinmemberNir Levy20-Dec-04 4:08 
AnswerRe: Quality? Pinsussshahab farooqui15-Oct-05 18:04 
QuestionHow to add labels to this pie chart sectors Pinmembersriamjunk31-Oct-04 23:54 
QuestionHow To Put Label Behind Per Pie Slices PinmemberbambooElbimbo9-Jul-04 16:02 
QuestionHow To Put Label Behind Per Pie Slices PinmemberbambooElbimbo9-Jul-04 15:50 
General3D Pie Chart in ASP.NET PinsussAnonymous25-May-04 3:31 
GeneralBug? Not your code PinmemberMrEyes2-Dec-03 6:59 
Generalquestion Pinmembernewmem2-Oct-03 12:04 
QuestionTruncated image display? Pinsussmsisson15-Sep-03 7:44 
GeneralBroken link PinsussAnonymous18-Aug-03 12:36 
QuestionIs there any way to add image to a listbox? Pinmemberdathq8-Aug-03 15:49 
AnswerRe: Is there any way to add image to a listbox? Pinmemberseewood29-Feb-04 20:43 
AnswerRe: Is there any way to add image to a listbox? PinmemberMJDamron13-Jan-06 6:22 
GeneralCode Typo: oibjBrush Pinmemberronemtz7-May-03 5:48 
GeneralNotice PinmemberMJDamron2-May-03 5:59 
GeneralRe: Notice PinmemberPVK8-May-03 10:48 
GeneralRe: Notice PinmemberMJDamron10-May-03 15:35 
GeneralRe: Notice PinmemberPVK12-May-03 6:55 
GeneralRe: Notice PinmemberNicejith26-Sep-07 0:47 

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
Web03 | 2.8.1411023.1 | Last Updated 28 Apr 2003
Article Copyright 2003 by MJDamron
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid