The code in this article is developed based on beta2
More and more web applications require charts for data display and analysis. 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. ASP. NET solves this problem. As long as you use ASP. NET's Graph Display classes, you can draw a wide range of dynamic charts (1 ). This article describes how to use ASP. NET technology and ADO. NET technology to draw bar charts and pie charts.
Figure 1
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 * 360;
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;
}
// Draw the 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 <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 );
Percent = convert. tosingle (Dt. Rows [I] [1])/consumer data * 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;
}
// Send the image content to the browser through response. outputstream
BM. Save (target, imageformat. GIF );
// Reclaim Resources
BM. Dispose ();
G. Dispose ();
}
}
// 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 there is not a 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_cs and add it to the Insight Project just now. Delete the default webform1.aspx file and create a new file named saleschart. aspx. Open this file and replace the first line:
<% @ Page contenttype = "image/GIF" Language = "C #" autoeventwireup = "false" codebehind = "saleschart. aspx. cs" inherits = "insight_cs.saleschart" %>
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
/// <Summary>
/// Required method for designer support-do not modify
/// The contents of this method with the code editor.
/// </Summary>
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:
Src = "saleschart. aspx? Type = pie & width = 300 & Height = 30
0 & Title = Sales + by + Year & subtitle = books ">
Src = "saleschart. aspx? Type = Bar & width = 300 & Height = 30
0 & Title = Sales + by + Year & subtitle = books ">
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.
The result shows 1 (the picture is in ASP. NET drawing Guide (I).
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.