Click here to Skip to main content
15,868,016 members
Articles / Web Development / ASP.NET
Article

3D Pie Chart in ASP.NET

Rate me:
Please Sign up or sign in to vote.
3.48/5 (27 votes)
27 Apr 20034 min read 334.8K   101   29
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:

C#
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.

C#
<%@ 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


Written By
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 ? Pin
Pankaj Garg14-Feb-14 10:16
Pankaj Garg14-Feb-14 10:16 
QuestionHow to See Chart ?? Pin
Ozgur KOC29-Dec-07 4:17
Ozgur KOC29-Dec-07 4:17 
AnswerRe: How to See Chart ?? Pin
Rajib Ahmed3-Mar-08 5:09
Rajib Ahmed3-Mar-08 5:09 
AnswerRe: How to See Chart ?? Pin
harshadcse22-Feb-13 22:07
harshadcse22-Feb-13 22:07 
QuestionHow to link it to the Database Pin
Sijo Mathew11-Oct-07 1:45
Sijo Mathew11-Oct-07 1:45 
QuestionBroken link yet again Pin
darksander19-Sep-07 4:14
darksander19-Sep-07 4:14 
GeneralFormula you were searching for Pin
Anthony Potts26-May-06 6:01
Anthony Potts26-May-06 6:01 
GeneralTypo Pin
paulanthony13-Feb-06 22:07
paulanthony13-Feb-06 22:07 
General3D Pie Edit Version with subtitle Pin
hockey223-May-05 22:00
hockey223-May-05 22:00 
GeneralRe: 3D Pie Edit Version with subtitle Pin
Belkira2-May-06 23:27
Belkira2-May-06 23:27 
What's this object ?

DataSet objDs = new Statistisc().SelectSaleRate(strNowYear);

Statistisc should be a class you developp ?D'Oh! | :doh:
QuestionQuality? Pin
Nir Levy20-Dec-04 3:08
Nir Levy20-Dec-04 3:08 
AnswerRe: Quality? Pin
Shahab Farooqui15-Oct-05 17:04
Shahab Farooqui15-Oct-05 17:04 
QuestionHow to add labels to this pie chart sectors Pin
Member 147430131-Oct-04 22:54
Member 147430131-Oct-04 22:54 
QuestionHow To Put Label Behind Per Pie Slices Pin
bambooElbimbo9-Jul-04 15:02
bambooElbimbo9-Jul-04 15:02 
QuestionHow To Put Label Behind Per Pie Slices Pin
bambooElbimbo9-Jul-04 14:50
bambooElbimbo9-Jul-04 14:50 
General3D Pie Chart in ASP.NET Pin
Anonymous25-May-04 2:31
Anonymous25-May-04 2:31 
GeneralBug? Not your code Pin
MrEyes2-Dec-03 5:59
MrEyes2-Dec-03 5:59 
Generalquestion Pin
newmem2-Oct-03 11:04
newmem2-Oct-03 11:04 
QuestionTruncated image display? Pin
msisson15-Sep-03 6:44
msisson15-Sep-03 6:44 
GeneralBroken link Pin
Anonymous18-Aug-03 11:36
Anonymous18-Aug-03 11:36 
QuestionIs there any way to add image to a listbox? Pin
dathq8-Aug-03 14:49
dathq8-Aug-03 14:49 
AnswerRe: Is there any way to add image to a listbox? Pin
seewood29-Feb-04 19:43
seewood29-Feb-04 19:43 
AnswerRe: Is there any way to add image to a listbox? Pin
MJDamron13-Jan-06 5:22
MJDamron13-Jan-06 5:22 
GeneralCode Typo: oibjBrush Pin
ronemtz7-May-03 4:48
ronemtz7-May-03 4:48 
GeneralNotice Pin
MJDamron2-May-03 4:59
MJDamron2-May-03 4:59 

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.