Use asp.net/c#to draw a pie chart and the source code of the line chart.

Source: Internet
Author: User
Tags getcolor
Chart. aspx. CS Code :
Using system;
Using system. collections;
Using system. componentmodel;
Using system. Data;
Using system. Web;
Using system. Web. sessionstate;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. htmlcontrols;
Using system. drawing;
Using system. Drawing. imaging;
Namespace aspcharts
{
///
/// Chart summary.
///
Public class chart: system. Web. UI. Page
{
Private void page_load (Object sender, system. eventargs E)
{





Graphics objgraphics; // creates a drawing board object.
Bitmap objbitmap = new Bitmap (600,300); // creates a bitmap object.
Objgraphics = graphics. fromimage (objbitmap); // creates a drawing board object based on the bitmap object.
Objgraphics. Clear (color. White); // sets the background color of the canvas object.
Int [] arrvalues = {0, 0, 0, 0, 0}; // data array
Arrvalues [0] = 50;
Arrvalues [1] = 70;
Arrvalues [2] = 90;
Arrvalues [3] = 100;
Arrvalues [4] = 140;
Arrvalues [5] = 220;
String [] arrvaluenames = {"0", "0", "0", "0", "0", "0"}; // month



Arrvaluenames [0] = "January ";
Arrvaluenames [1] = "February ";
Arrvaluenames [2] = "March ";
Arrvaluenames [3] = "February April ";
Arrvaluenames [4] = "February May ";
Arrvaluenames [5] = "June ";



Objgraphics. drawstring ("sales statistics for the first half", new font ("", 16), brushes. Black, new pointf ));



// Create legend text
Pointf symbolleg = new pointf (335,20 );



// Draw a legend. Draw a legend using three methods of the objgraphics graphic object:
// The fillrectangle () method draws the filled rectangle, and the drawrectangle () method draws the border of the rectangle,
// Draw instructions using the drawstring () method. The methods of these three graphical objects have been overloaded in the. NET Framework class library,
// You can easily draw images based on different parameters.



For (INT I = 0; I
{
Objgraphics. fillrectangle (New solidbrush (getcolor (I), symbolleg. X, symbolleg. Y, 20, 10 );



Objgraphics. drawrectangle (pens. Black, symbolleg. X, symbolleg. Y, 20, 10 );



Objgraphics. drawstring (arrvaluenames [I]. tostring (), new font ("", 10), brushes. Black, descleg );



Symbolleg. Y + = 15;
Descleg. Y + = 15;
}



For (Int J = 0; j
{
Objgraphics. fillrectangle (New solidbrush (getcolor (j), (J * 35) + 15,200-arrvalues [J], 20, arrvalues [J] + 5 );
Objgraphics. drawrectangle (pens. Black, (J * 35) + 15,200-arrvalues [J], 20, arrvalues [J] + 5 );
}



Float sglcurrentangle;
Float sgltotalangle = 0;



For (int A = 0; A <arrvalues. length; A ++)
{
Sgltotalangle + = arrvalues [a]; // obtain the total data volume.
}



Float startangle = 0;
For (INT B = 0; B <arrvalues. length; B ++)
{

Objgraphics. fillpie (New solidbrush (getcolor (B), 220, 95,100,100, startangle, sglcurrentangle); // draw an ellipse
Startangle + = sglcurrentangle;
}



Objbitmap. Save (response. outputstream, imageformat. GIF); // This bitmap object is output in "GIF" format.



}



Private color getcolor (INT itemindex)
{
Color objcolor = new color ();
Switch (itemindex)
{
Case 0:
Objcolor = color. blue;
Break;
Case 1:
Objcolor = color. Yellow;
Break;
Case 2:
Objcolor = color. Red;
Break;
Case 3:
Objcolor = color. Orange;
Break;
Case 4:
Objcolor = color. Purple;
Break;
Case 5:
Objcolor = color. Brown;
Break;
Case 6:



Default:
Objcolor = color. blue;
Break;
}



Return objcolor;
}



# Code generated by region web Form Designer
Override protected void oninit (eventargs E)
{
//
// Codegen: This call is required by the ASP. NET web form designer.
//
Initializecomponent ();
Base. oninit (E );
}



///
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
///
Private void initializecomponent ()
{
This. Load + = new system. eventhandler (this. page_load );
}
# Endregion
}
}



Use ASP. NET to draw bar charts and pie charts
[Abstract] More and more web applications need to use charts for data display and analysis. Using ASP. NET's graphics display classes, you can draw a wide range of dynamic charts.



The code in this article is developed based on beta2



For example, the voting result is displayed, and the company's production Statistical Chart is displayed and analyzed. Charts are used to display data, which is intuitive and clear.
Traditional ASP technology does not support drawing charts, so you have to use Active X or Java applets to implement this function. The emergence of ASP. NET solves this problem. As long as you use ASP. NET to display graphics classes, you can draw a wide range of dynamic charts. This article describes how to use ASP. NET technology and ADO. NET technology to draw bar charts and pie charts.



First, create a C # class library.
Open vs.net, create a new class library project named insight_cs.webcharts, change the solution name to insight, change the class. CS file name to insight_cs.webcharts.cs, and finally open the insight_cs.webcharts.cs file. The Code is as follows:
/* Custom classes. By entering different parameters, these classes can draw different images */



Using system;
Using system. IO; // used for File Access
Using system. Data; // used for data access
Using system. Drawing; // provides basic functions for drawing GDI + graphics.
Using system. Drawing. Text; // provides advanced functions for drawing GDI + graphics.
Using system. Drawing. drawing2d; // provides advanced 2D and vector graphics Functions.
Using system. Drawing. imaging; // provides advanced functions for drawing GDI + graphics.
Namespace insight_cs.webcharts
{
Public class piechart
{
Public piechart ()
{
}
Public void render (String title, string subtitle,
Int width, int height, dataset chartdata, stream target)
{
Const int side_length = 400;
Const int pie_diameter = 200;
Datatable dt = chartdata. Tables [0];



// Input parameters to obtain the total base in the pie chart
Float sumdata = 0;
Foreach (datarow DR in DT. Rows)
{
Sumdata + = convert. tosingle (Dr [1]);
}
// Generate an image object and generate a graphics object
Bitmap Bm = new Bitmap (width, height );
Graphics G = graphics. fromimage (BM );
// Set the properties of object g
G. scaletransform (convert. tosingle (width)/side_length,
(Convert. tosingle (height)/side_length );
G. smoothingmode = smoothingmode. default;
G. textrenderinghint = textrenderinghint. antialias;



// Canvas and edge settings
G. Clear (color. White );
G. drawrectangle (pens. Black, SIDE_LENGTH-1, SIDE_LENGTH-1 );
// Pie chart title
G. drawstring (title, new font ("tahoma", 24 ),
Brushes. Black, new pointf (5, 5 ));
// Pie chart legend
G. drawstring (subtitle, new font ("tahoma", 14 ),
Brushes. Black, new pointf (7, 35 ));
// Pie chart
Float curangle = 0;
Float totalangle = 0;
For (INT I = 0; I <DT. Rows. Count; I ++)
{
Curangle = convert. tosingle (Dt. Rows [I] [1])/sumdata * ;



G. fillpie (New solidbrush (chartutil. getchartitemcolor (I), 100,65, pie_diameter,
pie_diameter, totalangle, curangle);
G. drawpie (pens. black, 100,65, pie_diameter, pie_diameter,
totalangle, curangle);
totalangle + = curangle;
}< br> // draw a legend box and text
G. drawrectangle (pens. black, 200,300,199, 99);
G. drawstring ("legend", new font ("tahoma", 12, fontstyle. bold),
brushes. black, new pointf (200,300);



// draw legend items
pointf boxorigin = new pointf (210,330);
pointf textorigin = new pointf (235,326);
float percent = 0;
for (INT I = 0; I {< br> G. fillrectangle (New solidbrush (chartutil. getchartitemcolor (I),
boxorigin. x, boxorigin. y, 20,10);
G. drawrectangle (pens. black, boxorigin. x, boxorigin. y, 20,10);
percent = convert. tosingle (DT. rows [I] [1])/sumdata * 100;
G. drawstring (DT. rows [I] [0]. tostring () + "-" + dt. rows
[I] [1]. tostring () + "(" + percent. tostring ("0") + "%)", new font ("tahoma", 10), brushes. black, textorigin);
boxorigin. Y + = 15;
textorigin. Y + = 15;
}< br> // response. outputstream: sends the image content to the browser
BM. save (target, imageformat. GIF);
// reclaim resources
BM. dispose ();
G. dispose ();
}< BR >}



// Draw a bar chart
Public class barchart
{
Public barchart ()
{
}
Public void render (String title, string subtitle,
Int width, int height, dataset chartdata, stream target)
{
Const int side_length = 400;
Const int chart_top = 75;
Const int character height = 200;
Const int chart_left = 50;
Const int chart_width = 300;
Datatable dt = chartdata. Tables [0];



// Calculate the highest Vertex
Float highpoint = 0;
Foreach (datarow DR in DT. Rows)
{
If (highpoint <convert. tosingle (Dr [1])
{
Highpoint = convert. tosingle (Dr [1]);
}
}
// Create a graphics object instance
Bitmap Bm = new Bitmap (width, height );
Graphics G = graphics. fromimage (BM );
// Set graph and text attributes
G. scaletransform (convert. tosingle (width)/side_length,
(Convert. tosingle (height)/side_length );
G. smoothingmode = smoothingmode. default;
G. textrenderinghint = textrenderinghint. antialias;


// Set the canvas and edge
G. Clear (color. White );
G. drawrectangle (pens. Black, SIDE_LENGTH-1, SIDE_LENGTH-1 );
// Draw a large title
G. drawstring (title, new font ("tahoma", 24), brushes. Black, new pointf (5, 5 ));
// Draw a title
G. drawstring (subtitle, new font ("tahoma", 14 ),
Brushes. Black, new pointf (7, 35 ));
// Draw a bar chart
Float barwidth = chart_width/(dt. Rows. Count * 2 );
Pointf barorigin = new pointf (chart_left + (barwidth/2), 0 );
Float barheight = DT. Rows. count;
For (INT I = 0; I <DT. Rows. Count; I ++)
{
Barheight = convert. tosingle (Dt. Rows [I] [1]) * 200/highpoint;
Barorigin. Y = chart_top + chart_height-barheight;
G. fillrectangle (New solidbrush (chartutil. getchartitemcolor (I )),
Barorigin. X, barorigin. Y, barwidth, barheight );
Barorigin. x = barorigin. x + (barwidth * 2 );
}
// Set the edge
G. drawline (new pen (color. Black, 2), new point
(Chart_left, chart_top), new point (chart_left, chart_top + chart_height ));
G. drawline (new pen (color. Black, 2), new point
(Chart_left, chart_top + chart_height), new point
(Chart_left + chart_width, chart_top + chart_height ));
// Draw a legend box and text
G. drawrectangle (new pen (color. Black, 1), 200,300,199, 99 );
G. drawstring ("legend", new font ("tahoma", 12, fontstyle. Bold ),
Brushes. Black, new pointf (200,300 ));


// Draw a legend
Pointf boxorigin = new pointf (210,330 );
Pointf textorigin = new pointf (235,326 );
For (INT I = 0; I <DT. Rows. Count; I ++)
{
G. fillrectangle (New solidbrush (chartutil. getchartitemcolor (I )),
Boxorigin. X, boxorigin. Y, 20, 10 );
G. drawrectangle (pens. Black, boxorigin. X, boxorigin. Y, 20, 10 );
G. drawstring (Dt. Rows [I] [0]. tostring () + "-" + dt. Rows [I] [1].
Tostring (), new font ("tahoma", 10), brushes. Black, textorigin );
Boxorigin. Y + = 15;
Textorigin. Y + = 15;
}
// Output image
BM. Save (target, imageformat. GIF );



// Reclaim Resources
BM. Dispose ();
G. Dispose ();
}
}
Public class chartutil
{
Public chartutil ()
{
}
Public static color getchartitemcolor (INT itemindex)
{
Color selectedcolor;
Switch (itemindex)
{
Case 0:
Selectedcolor = color. blue;
Break;
Case 1:
Selectedcolor = color. Red;
Break;
Case 2:
Selectedcolor = color. Yellow;
Break;
Case 3:
Selectedcolor = color. Purple;
Break;
Default:
Selectedcolor = color. Green;
Break;
}
Return selectedcolor;
}
}
}


Code Analysis:
1. Introduce some namespaces
Using system;
Using system. IO; // used for File Access
Using system. Data; // used for data access
Using system. Drawing; // provides basic functions for drawing GDI + graphics.
Using system. Drawing. Text; // provides advanced functions for drawing GDI + graphics.
Using system. Drawing. drawing2d; // provides advanced 2D and vector graphics Functions.
Using system. Drawing. imaging; // provides advanced functions for drawing GDI + graphics.
These namespaces will be applied later.
2. Define a namespace as insight_cs.webcharts, which includes two classes: piechart and barchart. It is clear that class piechart is created for pie chart and class barchart is created for bar chart. Because the class piechart and class barchar are similar, we use a pie chart as an example to analyze the code.
3. Class piechart creates a method render, which can contain some parameters. Simple Description:
The title parameter indicates the title text above the pie chart.
The subtitle parameter indicates the title text above the pie chart.
The width and height parameters indicate the size of the entire image.
The chardata parameter is a DataSet object instance used for drawing.
The target parameter is an instance of the stream object, which is used for graphic output.
4. To increase readability, define some constants:
Const int side_length = 400; // canvas side length
Const int pie_diameter = 200; // pie chart diameter
5. Define a able, which is a data table in dataset. The data of the pie chart is stored.
6. Calculate the total base sumdata in the pie chart.
7. A Bitmap object is created, which provides memory space for the image to be created. Then, a graphics object is generated, which encapsulates the GDI + drawing interface.
8. Call the graphics object method scaletransform (), which is used to set the image proportion.
9. Call the smoothingmode () and textrenderinghint () Methods to set the attributes of text and graphics.
9. Set the canvas and edges.
10. Set the text title, legend, and pie chart.
11. Use stream to send the image content to the browser.
12. Finally, Recycle resources.


Now, the class of the pie chart is complete. The bar chart method is similar to the pie chart method.
In general, the class for building pictures is not as difficult as we think, and it is not very advanced.Algorithm. In fact, the overall idea is as if we use a pen to draw images on paper. The key is the use of each method and parameter settings.
We have already completed the customized pie chart and bar chart classes. We will apply these classes below.
Use vs.net to create a web application named insight_csProgramAnd add it to the Insight Project. Delete the default webform1.aspx file and create a new file named saleschart. aspx. Open this file and replace the first line:


Open the saleschart. aspx. CS file. The Code is as follows:
Using system;
Using system. Data;
Using system. Web;
Using system. IO;
Using system. Data. sqlclient;
Using insight_cs.webcharts; // This is a custom namespace
Namespace insight_cs
{
Public class saleschart: system. Web. UI. Page
{
Public saleschart ()
{
Page. init + = new system. eventhandler (page_init );
}
Private void page_load (Object sender, system. eventargs E)
{
// Obtain data from the database for drawing
String SQL = "select" + "Year (SA. ord_date) as [year], "+" sum (SA. qty) as [qty] "+" from "+" sales SA "+" inner join stores st on (SA. stor_id = ST. stor_id) "+" group by "+" Year (SA. ord_date) "+" order by "+" [year] ";
String connectstring = "Password = Ben; user id = sa; database = pubs; Data Source = localhost ";
Sqldataadapter da = new sqldataadapter (SQL, connectstring );
Dataset DS = new dataset ();
Int rows = da. Fill (DS, "chartdata ");
// Set the Graph Generation type (pie or bar)
String type = "";
If (null = request ["type"])
{
Type = "pie ";
}
Else
{
Type = request ["type"]. tostring (). toupper ();
}
// Set the image size
Int width = 0;
If (null = request ["width"])
{
Length = 400;
}
Else
{
Width = convert. toint32 (request ["width"]);
}
Int Height = 0;
If (null = request ["height"])
{
Height = 400;
}
Else
{
Height = convert. toint32 (request ["height"]);
}
// Set the chart title
String title = "";
If (null! = Request ["title"])
{
Title = request ["title"]. tostring ();
}
String subtitle = "";
If (null! = Request ["subtitle"])
{
Subtitle = request ["subtitle"]. tostring ();
}
If (0 <rows)
{
Switch (type)
{
Case "pie ":
Piechart Pc = new piechart ();
PC. Render (title, subtitle, width, height, DS, response. outputstream );
Break;
Case "bar ":
Barchart BC = new barchart ();
BC. Render (title, subtitle, width, height, DS, response. outputstream );
Break;
Default:


Break;
}
}
}
Private void page_init (Object sender, eventargs E)
{
//
// Codegen: This call is required by the ASP. NET web form designer.
//
Initializecomponent ();
}
# Region web form designer generated code
///


/// Required method for designer support-do not modify
/// The contents of this method with the code editor.
///


Private void initializecomponent ()
{
This. Load + = new system. eventhandler (this. page_load );
}
# Endregion
}
}
The above code is not difficult, so we will not analyze it here.
In vs.net, open insight_cs solution, right-click reference, and add reference to the component File insight_cs.webcharts.dll to make it the namespace in the project.
Now we can view the results.
First, create a demochart. aspx file and add the following content to the Code:

Type indicates the type of the graph, whether it is a pie chart pie or a bar chart.
Width and height indicate the image size.
Title indicates the title text.
Subtitle indicates the title text.
.



As a result, we have completed the process of drawing using Asp.net technology.
The following points can be summarized: 1. Using ASP. NET technology, you can draw an ideal image without using third-party components. 2. The core of drawing is to construct a bitmap object, which provides memory space for the image to be created. Then, draw a graph using the classes and methods provided by the namespace. Finally, you can call the "save" method of the bitmap object and send it to any. in the net output stream, the image content is directly sent to the browser without being saved to the disk.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.