Asp.net 畫圖(條形圖、折線圖、餅圖)

條形圖和餅圖是都要調用數據庫 而折線圖則是直接顯示不用調用數據庫

打開vs 工具 分別創建三中圖形的類 (BarChart、PieChart、zexian)ChartUtil類控制顏色

再建一個aspx 文件在後置文件中調用這個幾個類中的方法 本文章中有調用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;//用於數據訪問

using System.Drawing;//提供畫GDI+圖形的基本功能

using System.Drawing.Text;//提供畫GDI+圖形的高級功能

using System.Drawing.Drawing2D;//提供畫高級二維,矢量圖形功能

using System.Drawing.Imaging;
using System.IO;//提供畫GDI+圖形的高級功能
namespace Insight_cs.WebCharts
{
    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; //y軸最高點
            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);

            //設置條圖圖形和文字屬性
            //(Convert.ToSingle(width)將int 型類型對象轉換爲float類型
            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();

        }

    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;//用於數據訪問

using System.Drawing;//提供畫GDI+圖形的基本功能

using System.Drawing.Text;//提供畫GDI+圖形的高級功能

using System.Drawing.Drawing2D;//提供畫高級二維,矢量圖形功能

using System.Drawing.Imaging;
using System.IO;//提供畫GDI+圖形的高級功能

namespace Insight_cs.WebCharts
{
    public class PieChart
    {
          public PieChart()
            {

            }
        /// <summary>
        /// 畫餅圖
        /// </summary>
        /// <param name="title">餅圖要是顯示的大標題</param>
        /// <param name="subTitle"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="chartData"></param>
        /// <param name="target"></param>
            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();
            }
        }
    }

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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 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;

        }

    }
}

 

using System.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Web.SessionState;

using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace Insight_cs.WebCharts
{
    public class zexian
    {
        public zexian();
        public void rend()
        {
            /**/
            /*自寫編碼*/
            int ImgWidth = 600;        //1.[總寬度]            ***圖寬度  
            int ImgHeight = 300;        //2.[總高度]            ***圖高度       
            int ItemNum = 1;            //3.[項目數量]            ***圖表劃分的塊           
            int ChildNum = 6;            //4.[塊數]                ***大塊中劃分的子項的數量
            float ChildRate = 0.6f;    //5.[各塊總佔空間比率]
            //int ChildSpace=15;        //6.[各塊間的間距]
            int ChartLeft = 80;        //7.[圖表左邊距]        ***圖表距圖的左邊距離
            int ChartRight = 50;        //8.[圖表右邊距]        ***圖表距圖的右邊距離
            int ChartTop = 50;        //9.[圖表頂邊距]        ***圖表距圖頂邊距離
            int ChartBottom = 50;        //10.[圖表底邊距]        ***圖表距圖底邊距離
            int YMaxValue = 5000;        //11.[縱座標標尺最大值]    ***縱座標標尺的最大值
            int YItemNum = 10;        //12.[縱座標標尺段數]    ***縱座標標尺的段數
            int YTop = 15;            //13.[距縱軸頂端間隔]
            int YStrStart = 35;        //14.[縱座標標尺文字起始X座標]
            int XRight = 15;            //15.[距橫軸右端間隔]
            int XStrStart = 20;        //16.[橫座標標尺文字起始Y座標]


            //[圖表總寬度]=[總寬度]-[圖表左邊距]-[圖表右邊距]-[距橫軸右端間隔]
            int chartwidth = ImgWidth - ChartLeft - ChartRight - XRight;
            //[項目寬度]=[圖表總寬度]/[項目數量]
            int itemwidth = chartwidth / ItemNum;
            //[各塊總佔空間比率的實際寬度]=[項目寬度]*[各塊總佔空間比率]
            int factwidth = Convert.ToInt32(Math.Floor(itemwidth * ChildRate));
            //[各塊矩形寬度]=[各塊總佔空間比率的實際寬度]/[塊數]
            int rectanglewidth = factwidth / ChildNum;
            //[各塊間的間距]=([項目寬度]-[各塊總佔空間比率的實際寬度])/([塊數]+1)
            int childspace = Convert.ToInt32(Math.Floor(double.Parse(((itemwidth - factwidth) / (ChildNum + 1)).ToString())));

            Graphics objGps;//建立畫板對象
            Bitmap objBitMap = new Bitmap(ImgWidth, ImgHeight);//建立位圖對象
            objGps = Graphics.FromImage(objBitMap);//根據位圖對象建立畫板對象
            objGps.Clear(Color.White);//設置畫板對象的背景色


            //數組存放所有數據的集合 用於計算x/y軸的值
            int[] arrValues = { 0, 0, 0, 0, 0, 0 };//數據數組
            //arrValues[0]=500;
            arrValues[0] = Convert.ToInt32(Math.Floor(double.Parse(((ImgHeight - ChartBottom - ChartTop - YTop) * 300 / YMaxValue).ToString())));    //處理顯示數據,進行圖表數值對應
            arrValues[1] = Convert.ToInt32(Math.Floor(double.Parse(((ImgHeight - ChartBottom - ChartTop - YTop) * 700 / YMaxValue).ToString())));
            arrValues[2] = Convert.ToInt32(Math.Floor(double.Parse(((ImgHeight - ChartBottom - ChartTop - YTop) * 900 / YMaxValue).ToString())));
            arrValues[3] = Convert.ToInt32(Math.Floor(double.Parse(((ImgHeight - ChartBottom - ChartTop - YTop) * 1000 / YMaxValue).ToString())));
            arrValues[4] = Convert.ToInt32(Math.Floor(double.Parse(((ImgHeight - ChartBottom - ChartTop - YTop) * 1400 / YMaxValue).ToString())));
            arrValues[5] = Convert.ToInt32(Math.Floor(double.Parse(((ImgHeight - ChartBottom - ChartTop - YTop) * 2200 / YMaxValue).ToString())));
            //顯示於y軸上的標點
            string[] arrValueNames = { "0", "0", "0", "0", "0", "0", "0", "0", "0", "0" };//月份

            arrValueNames[0] = "一月";
            arrValueNames[1] = "二月";
            arrValueNames[2] = "三月";
            arrValueNames[3] = "四月";
            arrValueNames[4] = "五月";
            arrValueNames[5] = "六月";
            arrValueNames[6] = "七月";
            arrValueNames[7] = "八月";
            arrValueNames[8] = "九月";
            arrValueNames[9] = "十月";


            string[] xvaluename = new string[6] {
        "1","2","3","4","5","7"
        };
            //得出矩形寬度,和畫圖X軸位置

            //[項目寬度]=[總寬度]/[項目數量]
            //======[各塊總佔空間比率]=([各塊矩形寬度]+[各塊間的間距])/[項目寬度]
            //[各塊總佔空間比率的實際寬度]=[項目寬度]*[各塊總佔空間比率]
            //[各塊矩形寬度]=([各塊總佔空間比率的實際寬度]-[各塊間的間距]*([塊數]))/[塊數]
            //[一邊空餘空間寬度]=([項目寬度]-[各塊所佔空間比率的總寬度])/2 

            System.Drawing.Point[] pi = new Point[arrValues.Length];    //定義折線點的對象數組
            System.Drawing.Point[] pit = new Point[3];    //定義座標三角點的對象數組
            System.Drawing.Pen pe = new Pen(new SolidBrush(GetColor(7)), 1f);    //定義畫直線的對象
            //畫縱軸
            objGps.DrawLine(pe, new Point(ChartLeft, ImgHeight - ChartBottom), new Point(ChartLeft, ChartTop));
            //畫縱軸終點箭頭
            pit[0].X = ImgWidth - ChartRight;    //確定三角形三點的位置
            pit[0].Y = ImgHeight - ChartBottom - 4;
            pit[1].X = ImgWidth - ChartRight;
            pit[1].Y = ImgHeight - ChartBottom + 4;
            pit[2].X = ImgWidth - ChartRight + 10;
            pit[2].Y = ImgHeight - ChartBottom;
            objGps.FillPolygon(new SolidBrush(GetColor(7)), pit);
            //畫縱軸標尺和標尺描述
            for (int i = 1; i <= YItemNum; i++)
            {
                //畫標尺
                objGps.DrawLine(pe, new PointF(ChartLeft, ImgHeight - ChartBottom - (ImgHeight - ChartBottom - ChartTop - YTop) / YItemNum * i), new PointF(ChartLeft - 5, ImgHeight - ChartBottom - (ImgHeight - ChartBottom - ChartTop - YTop) / YItemNum * i));
                //畫描述
                objGps.DrawString(arrValueNames[i - 1].ToString(), new Font("宋體", 10), Brushes.Black, new Point(YStrStart, ImgHeight - ChartBottom - (ImgHeight - ChartBottom - ChartTop - YTop) / YItemNum * i - 5));
            }
            //畫橫軸
            objGps.DrawLine(pe, new Point(ChartLeft, ImgHeight - ChartBottom), new Point(ImgWidth - ChartRight, ImgHeight - ChartBottom));
            //畫橫軸終點箭頭
            pit[0].X = ChartLeft - 4;    //確定三角形三點的位置
            pit[0].Y = ChartTop;
            pit[1].X = ChartLeft + 4;
            pit[1].Y = ChartTop;
            pit[2].X = ChartLeft;
            pit[2].Y = ChartTop - 10;
            objGps.FillPolygon(new SolidBrush(GetColor(7)), pit);
            //畫橫軸標尺和標尺描述
            for (int i = 1; i <= ItemNum; i++)
            {
                //橫軸標尺
                objGps.DrawLine(pe, new PointF(ChartLeft + itemwidth * i, ImgHeight - ChartBottom), new PointF(ChartLeft + itemwidth * i, ImgHeight - ChartBottom + 5));
                //橫軸描敘

                objGps.DrawString(arrValueNames[i - 1].ToString(), new Font("宋體", 10), Brushes.Black, new Point(ChartLeft + childspace + itemwidth * (i - 1), ImgHeight - ChartBottom + XStrStart));
            }


            for (int j = 0; j < arrValues.Length; j++)//畫矩形圖和折線圖
            {
                //畫條形圖
                objGps.FillRectangle(new SolidBrush(GetColor(j)), (j * (childspace + rectanglewidth)) + childspace + ChartLeft, ImgHeight - ChartBottom - arrValues[j], rectanglewidth, arrValues[j]);
                objGps.DrawRectangle(Pens.Black, (j * (childspace + rectanglewidth)) + childspace + ChartLeft, ImgHeight - ChartBottom - arrValues[j], rectanglewidth, arrValues[j]);
                //畫折線圖
                pi[j].X = (j * (childspace + rectanglewidth)) + childspace + ChartLeft;
                pi[j].Y = ImgHeight - ChartBottom - arrValues[j];
                pe.SetLineCap(System.Drawing.Drawing2D.LineCap.RoundAnchor, System.Drawing.Drawing2D.LineCap.RoundAnchor, System.Drawing.Drawing2D.DashCap.Round);
                if (j > 0)
                {
                    objGps.DrawLine(pe, pi[j - 1], pi[j]);
                }
            }

            objBitMap.Save(Response.OutputStream, ImageFormat.Gif);//該位圖對象以"GIF"格式輸出
        }
        /**/
        /// <param name="itemIndex">系統定義的顏色,有效值0到7,分別爲(Blue,Yellow,Red,Orange,Purple,Brown,Pink,Black)</param>
        /// <returns></returns>
        public static 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:
                    objColor = Color.Pink;
                    break;
                default:
                    objColor = Color.Black;
                    break;
            }

            return objColor;
        }

        /**/
        /// <param name="red">自定義顏色紅色分量值,有效值0到255</param>
        /// <param name="green">自定義顏色綠色分量值,有效值0到255</param>
        /// <param name="blue">自定義顏色藍色分量值,有效值0到255</param>
        /// <returns></returns>
        public static Color GetColor(int red, int green, int blue)
        {
            Color objColor = new Color();
            objColor = Color.FromArgb(red, green, blue);
            return objColor;
        }
    }
}

 

條形圖和餅圖的調用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using klzx.NoteFlatrootSys.DAL;

using System.Text;
using System.Data.SqlClient;
using Insight_cs.WebCharts;

 

public partial class drawpicture : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Init += new System.EventHandler(Page_Init);
    }
    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


    /// <summary>
    /// 調用餅圖
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_Click(object sender, EventArgs e)
    {
        DataSet ds = getds();
        PieChart pc = new PieChart();
        pc.Render("aa", "bb", 400, 500, ds, Response.OutputStream);
    }

    private static DataSet getds()
    {
        string sql = "select Year(s.statDate) As [Year],sum(s.total) as 總髮送 from smsstat s inner join smsjob j on (s.jobid=j.jobid)group  by Year(s.statDate) ";
        DataSet ds = new DataSet();
        ds = DBHelper.GetDataSet1(sql);
        return ds;
    }
    /// <summary>
    /// 條形圖
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataSet ds = getds();
        BarChart bc = new BarChart();
        bc.Render("b", "", 400, 500, ds, Response.OutputStream);       
    }
}

發佈了49 篇原創文章 · 獲贊 4 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章