[C#]畫圖全攻略(餅圖與柱狀圖)(轉)

來源:互聯網
上載者:User

標籤:

http://blog.chinaunix.net/uid-15481846-id-2769484.html

首先建立一個c#的類庫。
  開啟vs.net,建立一個名為Insight_cs.WebCharts新的類庫工程,將解決方案的名稱改為Insight,將Class.cs檔案名稱改為Insight_cs.WebCharts.cs,最後開啟Insight_cs.WebCharts.cs檔案。其中代碼如下:
  /*自訂類,通過輸入不同的參數,這些類可以畫不同的圖形 */
   
  using System;
  using System.IO;//用於檔案存取
  using System.Data;//用於資料訪問
  using System.Drawing;//提供畫GDI+圖形的準系統
  using System.Drawing.Text;//提供畫GDI+圖形的進階功能
  using System.Drawing.Drawing2D;//提供畫進階二維,向量圖形功能
  using System.Drawing.Imaging;//提供畫GDI+圖形的進階功能
  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];
   
   //通過輸入參數,取得餅圖中的總基數
   float sumData = 0;
   foreach(DataRow dr in dt.Rows)
   {
   sumData += Convert.ToSingle(dr[1]);
   }
   //產生一個image對象,並由此產生一個Graphics對象
   Bitmap bm = new Bitmap(width,height);
   Graphics g = Graphics.FromImage(bm);
   //設定對象g的屬性
   g.ScaleTransform((Convert.ToSingle(width))/SIDE_LENGTH,(Convert.ToSingle(height))/SIDE_LENGTH);
   g.SmoothingMode = SmoothingMode.Default;
   g.TextRenderingHint = TextRenderingHint.AntiAlias;
   
   //畫布和邊的設定
   g.Clear(Color.White);
   g.DrawRectangle(Pens.Black,0,0,SIDE_LENGTH-1,SIDE_LENGTH-1);
   //畫餅表徵圖題
   g.DrawString(title,new Font("Tahoma",24),Brushes.Black,new PointF(5,5));
   //畫餅圖的圖例
   g.DrawString(subTitle,new Font("Tahoma",14),Brushes.Black,new PointF(7,35));
   //畫餅圖
   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;
   }
   //畫圖例框及其文字
   g.DrawRectangle(Pens.Black,200,300,199,99);
   g.DrawString("Legend",new Font("Tahoma",12,FontStyle.Bold),Brushes.Black,new PointF(200,300));
   
   //畫圖例各項
   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",10),Brushes.Black,textOrigin);
   boxOrigin.Y += 15;
   textOrigin.Y += 15;
   }
   //通過Response.OutputStream,將圖形的內容發送到瀏覽器
   bm.Save(target, ImageFormat.Gif);
   //回收資源
   bm.Dispose();
   g.Dispose();
   }
   }
   
  //畫橫條圖
   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];
   
   //計算最高的點
   float highPoint = 0;
   foreach(DataRow dr in dt.Rows)
   {
   if(highPoint<Convert.ToSingle(dr[1]))
   {
   highPoint = Convert.ToSingle(dr[1]);
   }
   }
   //建立一個Graphics對象執行個體
   Bitmap bm = new Bitmap(width,height);
   Graphics g = Graphics.FromImage(bm);
   //設定條圖圖形和文字屬性
   g.ScaleTransform((Convert.ToSingle(width))/SIDE_LENGTH,(Convert.ToSingle(height))/SIDE_LENGTH);
   g.SmoothingMode = SmoothingMode.Default;
   g.TextRenderingHint = TextRenderingHint.AntiAlias;
   
   //設定畫布和邊
   g.Clear(Color.White);
   g.DrawRectangle(Pens.Black,0,0,SIDE_LENGTH-1,SIDE_LENGTH-1);
   //畫大標題
   g.DrawString(title,new Font("Tahoma",24),Brushes.Black,new PointF(5,5));
   //畫小標題
   g.DrawString(subTitle,new Font("Tahoma",14),Brushes.Black,new PointF(7,35));
   //畫橫條圖
   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);
   }
   //設定邊
   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));
   //畫圖例框和文字
   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));
   
   //畫圖例
   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;
   }
   //輸出圖形
   bm.Save(target, ImageFormat.Gif);
   
   //資源回收
   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;
   }
   }
  }
   
  程式碼分析:
  1.引入一些namespace
  using System;
  using System.IO;//用於檔案存取
  using System.Data;//用於資料訪問
  using System.Drawing;//提供畫GDI+圖形的準系統
  using System.Drawing.Text;//提供畫GDI+圖形的進階功能
  using System.Drawing.Drawing2D;//提供畫進階二維,向量圖形功能
  using System.Drawing.Imaging;//提供畫GDI+圖形的進階功能
  這些namespace將在後面被應用。
  2.自訂一個namespace為Insight_cs.WebCharts,其中包括了兩個類PieChart和BarChart,很清楚,class PieChart是為畫餅圖而建,class BarChart是為畫橫條圖而建。由於class PieChart和class BarChar差不多,所以下面我們以餅圖為例,進行程式碼分析。
  3.類PieChart建立一個方法Render,此方法可以含一些參數。簡單說明如下:
  參數title,表示餅圖上方的大標題文字。
  參數subtitle,表示餅圖上方的小標題文字。
  參數width,height,表示了整個圖形的大小。
  參數charData是一個DataSet對象執行個體,用於畫圖使用。
  參數target是Stream對象的執行個體,用於圖形輸出時使用。
  4.為了增加可讀性,定義一些常量:
  const int SIDE_LENGTH = 400;//畫布邊長
  const int PIE_DIAMETER = 200;//餅圖直徑
  5.定義一個DataTable,它是DataSet中的一個資料表。其中存放了餅圖的各個資料。
  6.通過計算,得出餅圖中的總基數sumData。
  7.建立了一個BitMap對象,它為要建立的圖形提供了記憶體空間。並由此產生一個Graphics對象,它封裝了GDI+畫圖介面。
  8.調用Graphics對象的方法ScaleTransform(),它是用來設定圖形比例的。
  9.調用方法SmoothingMode(),TextRenderingHint()等來設定文字和圖形的相關屬性。
  9.設定畫布和邊。
  10.設定文字標題,圖例,畫餅圖自身。
  11.通過Stream,將圖形的內容發送到瀏覽器。
  12.最後回收資源。
   
  至此畫餅圖的類就完成了。畫橫條圖的方法和畫餅圖的方法大同小異,這裡就不展開講了。
  總體看來,構建畫圖的類沒有我們想象的那樣難,並沒有多麼高深的演算法。其實整體思路,就好像我們用筆在紙上畫圖是一摸一樣的。關鍵是各個方法的使用和參數設定。
   
   
   
   

     我們在前面已經完成了餅圖和橫條圖的自訂類,下面我們將要應用這些類了。
  使用vs.net建立一個名為Insight_cs的Web應用程式,並且添加到剛才的Insight工程中。刪除預設的webform1.aspx檔案,建立一個名為SalesChart.aspx檔案。開啟此檔案,在代碼模式下,將第一行替換為:
  <%@ Page ContentType="image/gif" Language="c#" AutoEventWireup="false" Codebehind="SalesChart.aspx.cs" Inherits="Insight_cs.SalesChart" %>
  開啟檔案SalesChart.aspx.cs,其中代碼如下所示:
  using System;
  using System.Data;
  using System.Web;
  using System.IO;
  using System.Data.SqlClient;
  using Insight_cs.WebCharts;//這是自訂的名字空間
  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)
   {
   //從資料庫中取得資料,用於畫圖
   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");
   //設定產生圖的類型(pie or bar)
   string type = "";
   if(null==Request["type"])
   {
   type = "PIE";
   }
   else
   {
   type = Request["type"].ToString().ToUpper();
   }
   //設定圖大小
   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"]);
   }
   //設定圖表標題
   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
   }
  }
  以上的代碼並沒有什麼難的,這裡就不做分析了。
  在vs.net中,開啟Insight_cs solution,右擊”引用“,將出現”添加引用“,將組件檔案Insight_cs.WebCharts.dll加入,使其成為項目中的namespace。
  下面我們就可以瀏覽結果了。
  首先建立一個demochart.aspx檔案,在其代碼中,加入一下內容:
  <IMG alt="Sales Data - Pie"
  src="SalesChart.aspx?type=pie&width=300&height=30
  0&title=Sales+by+Year&subtitle=Books">
  <IMG alt="Sales Data - Bar"
  src="SalesChart.aspx?type=bar&width=300&height=30
  0&title=Sales+by+Year&subtitle=Books">
  type表示顯示圖形的類型,是餅圖pie,還是橫條圖bar。
  width,height表示圖形的大小。
  title表示大標題文字。
  subtitle表示小標題文字。
  其結果顯示1(圖片在文章《ASP.NET畫圖全攻略(上)》)。
   
  由此,我們完成了利用asp.net技術畫圖的過程。
  綜合起來,可以總結出以下幾點:1.利用ASP.NET技術,可以在不使用第三方組件的情況下,畫出理想的圖形。2.畫圖核心是構造一個BitMap(位元影像)對象,它為要建立的圖形提供了記憶體空間。然後,利用有關namespace提供的類和方法畫出圖形。最後就可以調用Bitmap對象的“Save”方法,將其發送到任何.NET的輸出資料流中,這裡是直接將圖形的內容發送到瀏覽器,而沒有將其儲存到磁碟中。

[C#]畫圖全攻略(餅圖與柱狀圖)(轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.