Http://blog.chinaunix.net/uid-15481846-id-2769484.html
First, create a C # class library.
Open Vs.net and set up a name of Insight_cs. Webcharts the new Class library project, change the name of the solution to insight and change the Class.cs file name to Insight_cs. WebCharts.cs, finally open Insight_cs. WebCharts.cs file. Where the code is as follows:
/* Custom classes, these classes can draw different shapes by entering different parameters */
Using System;
Using system.io;//for file access
Using system.data;//for data access
Using system.drawing;//provides the basic functions of drawing GDI + graphics
Using system.drawing.text;//provides advanced features for drawing GDI + graphics
Using system.drawing.drawing2d;//provides advanced two-dimensional, vector graphics features
Using system.drawing.imaging;//provides advanced features 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];
Get the total cardinality in the pie chart by entering parameters
float sumdata = 0;
foreach (DataRow dr in Dt. Rows)
{
Sumdata + = Convert.tosingle (dr[1]);
}
Produces an image object, and thus produces a graphics object
Bitmap BM = new Bitmap (width,height);
Graphics g = graphics.fromimage (BM);
Set properties for Object G
G.scaletransform ((Convert.tosingle (width))/side_length, (convert.tosingle (height))/side_length);
G.smoothingmode = Smoothingmode.default;
G.textrenderinghint = Textrenderinghint.antialias;
Settings for canvas and Edge
G.clear (Color.White);
G.drawrectangle (pens.black,0,0,side_length-1,side_length-1);
appeased Chart Title
g.DrawString (title,new Font ("Tahoma"), Brushes.black,new PointF (5,5));
Legend of the appeased chart
g.DrawString (subtitle,new Font ("Tahoma", +), Brushes.black,new PointF (7,35));
appeased 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;
}
Drawing Example Box and its text
G.drawrectangle (pens.black,200,300,199,99);
g.DrawString ("Legend", New Font ("Tahoma", 12,fontstyle.bold), Brushes.black,new PointF (200,300));
Drawing example 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])/sumdata * 100;
g.drawstring (dt. Rows[i][0]. ToString () + "-" + dt. ROWS[I][1]. ToString () + "(" + percent. ToString ("0") + "%", new Font ("Tahoma", "ten"), Brushes.black,textorigin);
BOXORIGIN.Y + = 15;
TEXTORIGIN.Y + = 15;
}
Send the contents of the graphic to the browser via Response.outputstream
Bm. Save (target, imageformat.gif);
Recycling 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 chart_height = 200;
const int chart_left = 50;
const int chart_width = 300;
DataTable dt = chartdata.tables[0];
Calculate the highest point
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 bar graph graphics and Text properties
G.scaletransform ((Convert.tosingle (width))/side_length, (convert.tosingle (height))/side_length);
G.smoothingmode = Smoothingmode.default;
G.textrenderinghint = Textrenderinghint.antialias;
Setting the canvas and edges
G.clear (Color.White);
G.drawrectangle (pens.black,0,0,side_length-1,side_length-1);
Draw Big Headlines
g.DrawString (title,new Font ("Tahoma"), Brushes.black,new PointF (5,5));
Draw a small title
g.DrawString (subtitle,new Font ("Tahoma", +), 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 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));
Drawing example Boxes 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));
Drawing example
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", "ten"), Brushes.black,textorigin);
BOXORIGIN.Y + = 15;
TEXTORIGIN.Y + = 15;
}
Output graphics
Bm. Save (target, imageformat.gif);
Resource Recycling
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. Introduction of some namespace
Using System;
Using system.io;//for file access
Using system.data;//for data access
Using system.drawing;//provides the basic functions of drawing GDI + graphics
Using system.drawing.text;//provides advanced features for drawing GDI + graphics
Using system.drawing.drawing2d;//provides advanced two-dimensional, vector graphics features
Using system.drawing.imaging;//provides advanced features for drawing GDI + graphics
These namespace will be applied at the back.
2. Customize a namespace for Insight_cs. Webcharts, which includes two classes of Piechart and Barchart, it is clear that class Piechart is built for appeased diagrams, and class Barchart is for drawing bar charts. Since class Piechart and class Barchar are similar, let's take a pie chart as an example for code analysis.
3. Class Piechart Create a method render, this method can contain some parameters. A brief description is as follows:
The title of the parameter, which represents the large headline text above the pie chart.
A parameter subtitle that represents the small caption text above the pie chart.
The parameter width,height, which represents the size of the entire shape.
The parameter chardata is a DataSet object instance that is used for paint use.
The parameter target is an instance of the stream object that is used for graphical output.
4. To add readability, define some constants:
const int side_length = 400;//Canvas Edge length
const int pie_diameter = 200;//pie chart diameter
5. Define a DataTable, which is a data table in the dataset. It stores the individual data for the pie chart.
6. The total cardinality sumdata in the pie chart is obtained by calculation.
7. A Bitmap object is created that provides a memory space for the graphics to be created. This produces a graphics object that encapsulates the GDI + drawing interface.
8. Call the Graphics object's method ScaleTransform (), which is used to set the graph scale.
9. Call Method SmoothingMode (), TextRenderingHint (), and so on to set the related properties of text and graphics.
9. Set the canvas and edges.
10. Set the text title, legend, appeased diagram itself.
11. Via stream, send the contents of the graphic to the browser.
12. Final recovery of resources.
The class of the appeased diagram is now complete. The method of drawing bar chart and the method of appeased diagram are very similar, so we don't start talking here.
In general, the class of drawing is not as difficult as we think, and it doesn't have much of an advanced algorithm. In fact, the whole idea, as if we use a pen on paper to draw is a touch. The key is the use of each method and the parameter settings.
We've already completed the custom classes for pie and bar charts, and we're going to apply these classes.
Use Vs.net to create a new 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 in code mode, replace the first line with the following:
<%@ page contenttype= "image/gif" language= "C #" autoeventwireup= "false" codebehind= "SalesChart.aspx.cs" inherits= " Insight_cs. Saleschart "%>
Open the file SalesChart.aspx.cs, where the code looks like this:
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)
{
Get data from a 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 type of generating graph (pie or bar)
String type = "";
if (null==request["type"])
{
Type = "PIE";
}
Else
{
Type = request["type"]. ToString (). ToUpper ();
}
Set Diagram size
int width = 0;
if (null==request["width"])
{
width = 400;
}
Else
{
width = Convert.ToInt32 (request["width"]);
}
int height = 0;
if (null==request["height"])
{
Height = 400;
}
Else
{
Height = Convert.ToInt32 (request["height"]);
}
Set 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 was required by the 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, and there is no analysis.
In Vs.net, open Insight_cs solution, right-click on "References", "Add Reference" will appear, and the component file will be insight_cs. WebCharts.dll joined to make it the namespace in the project.
Below we can see the results.
First create a demochart.aspx file, and in its code, add something:
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 whether the shape is displayed, pie, or bar bar.
Width,height represents the size of the graphic.
Title indicates the headline text.
Subtitle represents the small caption text.
The results show 1 (picture in the article "ASP." NET drawing (above) ").
As a result, we have completed the process of drawing using ASP.
Together, the following points can be summed up: 1. With ASP. NET technology, you can draw ideal graphics without using third-party components. 2. The drawing core is the construction of a bitmap (bitmap) object, which provides a memory space for the graphics to be created. Then, draw the graph using the classes and methods provided by the namespace. Finally, you can call the "Save" method of the bitmap object to send it to any. NET in the output stream, where the contents of the graphic are sent directly to the browser without saving it to disk.
[C #] Draw all tips (pie chart and histogram) (GO)