[C#]画图全攻略

上传人:优*** 文档编号:39616694 上传时间:2021-11-11 格式:DOC 页数:58 大小:241KB
返回 下载 相关 举报
[C#]画图全攻略_第1页
第1页 / 共58页
[C#]画图全攻略_第2页
第2页 / 共58页
[C#]画图全攻略_第3页
第3页 / 共58页
点击查看更多>>
资源描述
真诚为您提供优质参考资料,若有不当之处,请指正。 本文代码是基于Beta2开发 越来越多的Web应用需要使用图表来进行数据显示和分析。例如:投票结果显示,公司生产情况统计图显示分析等等。利用图表来显示数据,具有直观,清晰等优点。 传统的ASP技术是不支持画图表的,那么就不得不利用Active X或者Java applets来实现这个功能。新近出现的ASP.NET解决了这个问题,只要利用ASP.NET中关于图形显示的类,就可以画出丰富,动态的图表(如图1)。本文将要讲述如何利用ASP.NET技术结合ADO.NET技术画条形图和饼图。 图1 首先建立一个c#的类库。 打开,建立一个名为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.Tables0; /通过输入参数,取得饼图中的总基数 float sumData = 0; foreach(DataRow dr in dt.Rows) sumData += Convert.ToSingle(dr1); /产生一个image对象,并由此产生一个Graphics对象 1 / 58 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;idt.Rows.Count;i+) curAngle = Convert.ToSingle(dt.Rowsi1) / 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;idt.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.Rowsi1) / sumData * 100; g.DrawString(dt.Rowsi0.ToString() + - + dt.Rowsi1.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.Tables0; /计算最高的点 float highPoint = 0; foreach(DataRow dr in dt.Rows) if(highPointConvert.ToSingle(dr1) highPoint = Convert.ToSingle(dr1); /建立一个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;idt.Rows.Count;i+) barHeight = Convert.ToSingle(dt.Rowsi1) * 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;idt.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.Rowsi0.ToString() + - + dt.Rowsi1.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.最后回收资源。 至此画饼图的类就完成了。画条形图的方法和画饼图的方法大同小异,这里就不展开讲了。 总体看来,构建画图的类没有我们想象的那样难,并没有多么高深的算法。其实整体思路,就好像我们用笔在纸上画图是一摸一样的。关键是各个方法的使用和参数设置。 我们在前面已经完成了饼图和条形图的自定义类,下面我们将要应用这些类了。 使用新建一个名为Insight_cs的Web应用程序,并且添加到刚才的Insight工程中。删除默认的webform1.aspx文件,新建一个名为SalesChart.aspx文件。打开此文件,在代码模式下,将第一行替换为: 打开文件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=Requesttype) type = PIE; else type = Requesttype.ToString().ToUpper(); /设置图大小 int width = 0; if(null=Requestwidth) width = 400; else width = Convert.ToInt32(Requestwidth); int height = 0; if(null=Requestheight) height = 400; else height = Convert.ToInt32(Requestheight); /设置图表标题 string title = ; if(null!=Requesttitle) title = Requesttitle.ToString(); string subTitle = ; if(null!=Requestsubtitle) subTitle = Requestsubtitle.ToString(); if(0rows) 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 以上的代码并没有什么难的,这里就不做分析了。 在中,打开Insight_cs solution,右击”引用“,将出现”添加引用“,将组件文件Insight_cs.WebCharts.dll加入,使其成为项目中的namespace。 下面我们就可以浏览结果了。 首先建立一个demochart.aspx文件,在其代码中,加入一下内容: type表示显示图形的类型,是饼图pie,还是条形图bar。 width,height表示图形的大小。 title表示大标题文字。 subtitle表示小标题文字。 其结果显示如图1(图片在文章ASP.NET画图全攻略(上)。 由此,我们完成了利用技术画图的过程。 综合起来,可以总结出以下几点:1.利用ASP.NET技术,可以在不使用第三方组件的情况下,画出理想的图形。2.画图核心是构造一个BitMap(位图)对象,它为要创建的图形提供了内存空间。然后,利用有关namespace提供的类和方法画出图形。最后就可以调用Bitmap对象的“Save”方法,将其发送到任何.NET的输出流中,这里是直接将图形的内容发送到浏览器,而没有将其保存到磁盘中。 本文来自CSDN博客,转载请标明出处:C#画图GDI Grphic作者:Lynn 日期:2009-03-12字体大小: 小 中 大GDI是Graphics Device Interface的缩写,含义是图形设备接口,它的主要任务是负责系统与绘图程序之间的信息交换,处理所有Windows程序的图形输出。 在Windows操作系统下,绝大多数具备图形界面的应用程序都离不开GDI,我们利用GDI所提供的众多函数就可以方便的在屏幕、打印机及其它输出设备上输出图形,文本等操作。GDI的出现使程序员无需要关心硬件设备及设备驱动,就可以将应用程序的输出转化为硬件设备上的输出,实现了程序开发者与硬件设备的隔离,大大方便了开发工作。 GDI是如何实现输出的? 要想在屏幕或者其它输出设备上输出图形或者文字,那么我们就必须先获得一个称为设备描述表( DC:Device Context)的对象的句柄,以它为参数,调用各种GDI函数实现各种文字或图形的输出。设备描述表是GDI内部保存数据的一种数据结构,此结构中的属性内容与特定的输出设备(显示器,打印机等)相关,属性定义了GDI函数的工作细节,在这里属性确定了文字的颜色,x坐标和y坐标映射到窗口显示区域的方式等。 设备描述表句柄一旦获得,那么系统将使用默认的属性值填充设备描述表结构。 如果有必要,我们可以使用一些GDI函数获取和改变设备描述表中的属性值。 1.位图上绘制点和线System.Drawing.Image MyImage=new System.Drawing.Bitmap (w,h);/申请位图对象System.Drawing.Graphics g=System.Drawing.Graphics.FromImage(MyImage); /申请画图对象/用白色C清出除Color C=Color.FromArgb(255,255,255);g.Clear(C); /画线g.DrawLine(Pens.Black,x1,y1,x2,y2);/画一个象素的点/MyBitmap.SetPixel(x, y, Color.White);g.DrawImage(MyImage,0,0,h,w); /pictureBox1在(0,0)到(h,w)范围画点pictureBox1.Image=MyImage; /这个图片贴到pictureBox1控件上2.在窗体上绘制图形System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red);/画笔System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);/画刷System.Drawing.Graphics formGraphics = this.CreateGraphics();formGraphics.FillEllipse(myBrush, new Rectangle(0,0,100,200);/画实心椭圆formGraphics.DrawEllipse(myPen, new Rectangle(0,0,100,200);/空心圆formGraphics.FillRectangle(myBrush, new Rectangle(0,0,100,200);/画实心方formGraphics.DrawRectangle(myPen, new Rectangle(0,0,100,200);/空心矩形formGraphics.DrawLine(myPen, 0, 0, 200, 200);/画线formGraphics.DrawPie(myPen,90,80,140,40,120,100); /画馅饼图形 /画多边形 formGraphics.DrawPolygon(myPen,new Point new Point(30,140), new Point(270,250), new Point(110,240), new Point(200,170), new Point(70,350), new Point(50,200); /清理使用的资源myPen.Dispose();myBrush.Dispose();formGraphics.Dispose();3.在窗体上绘制文本/在窗体上绘制竖向文本 System.Drawing.Graphics formGraphics = this.CreateGraphics();string drawString = Text;System.Drawing.Font drawFont = new System.Drawing.Font(Arial, 16);System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);float x = 150.0f;float y = 50.0f;System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat(StringFormatFlags.DirectionVertical);/文本垂直formGraphics.DrawString(drawString, drawFont, drawBrush, x, y);/绘制文本formGraphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);/绘制垂直文本/清理使用的资源drawFont.Dispose();drawBrush.Dispose();formGraphics.Dispose();4.其他画笔/该画刷的HatchStyle有DiagonalCross、 ForwardDiagonal、Horizontal、 Vertical、 Solid等不同风格 HatchStyle hs = HatchStyle.Cross; /十字HatchBrush sb = new HatchBrush(hs,Color.Blue,Color.Red); g.FillRectangle(sb,50,50,150,150); Rectangle r = new Rectangle(500, 300, 100, 100); LinearGradientBrush lb = new LinearGradientBrush(r, Color.Red, Color.Yellow, LinearGradientMode.BackwardDiagonal); g.FillRectangle(lb, r); /PathGradientBrush路径渐变,LinearGradientBrush线性渐变Image bgimage = new Bitmap(E:2065215396.jpg); brush = new TextureBrush(bgimage); /易一幅图作椭圆的背景 g.FillEllipse(brush,50,50,500,300);5.其他技巧/申请画图区域System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(100, 100, 200, 200);/创建笔System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Black);myPen.DashStyle=DashStyle.Dash /DashStyle有Dash、DashDot、DashDotDot、Dot、Solid等风格/创建单色画刷System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);/画图函数protected override void OnPaint ( System.Windows.Forms.PaintEventArgs e ) /颜色对话框ColorDialog c = new ColorDialog(); c.ShowDialog(); textBox1.BackColor = c.Color; /字体对话框FontDialog f = new FontDialog(); f.ShowDialog(); textBox1.Font = flg.Font; /RGB的使用int Red=(int)SelfPlaceKey.GetValue(Red);int Green=(int)SelfPlaceKey.GetValue(Green);int Blue=(int)SelfPlaceKey.GetValue(Blue);BackColor=Color.FromArgb(Red,Green,Blue);/字体Font aFont=new Font(Arial,16,FontStyle.Bold|FontStyle.Italic);rect=new Rectangle(0,y,400,aFont.Height);g.DrawRectangle(Pens.Blue,rect);StringFormat sf=new StringFormat();sf.Alignment=StringAlignment.Far;g.DrawString(This text is right justified.,aFont,Brushes.Blue,rect,sf);y+=aFont.Height+20;aFont.Dispose();C# 画图(1) protected override void OnPaint(PaintEventArgs paintEvnt) /获取画板 Graphics gfx = paintEvnt.Graphics; / 构造画笔 Pen myPen = new Pen(Color.Black); / 画线 for (int i = 20; i 250; i = i + 10) gfx.DrawLine(myPen, 20, i, 270, i); 垂直画一遍,画出方格:protectedoverridevoidOnPaint(PaintEventArgspaintEvnt) /Getthegraphicsobject Graphicsgfx=paintEvnt.Graphics; /Createanewpenthatweshallusefordrawingtheline PenmyPen=newPen(Color.Black); /Loopandcreateahorizontalline10pixelsbelowthelastone for(inti=20;i=250;i=i+10) gfx.DrawLine(myPen,20,i,270,i); /Loopandcreateaverticalline10pixelsnexttothelastone for(intx=20;x280;x=x+10) gfx.DrawLine(myPen,x,20,x,250); 画方框:protectedoverridevoidOnPaint(PaintEventArgspaintEvnt) /Getthegraphicsobject Graphicsgfx=paintEvnt.Graphics; /Createanewpenthatweshallusefordrawingtheline PenmyPen=newPen(Color.Black); /Loopuntilthecoordinatesreach250(thelowerrightcorneroftheform) for(inti=0;i250;i=i+50) /Drawa50x50pixelsrectangle gfx.DrawRectangle(myPen,i,i,50,50); 循环,画渐变色 protected override void OnPaint(PaintEventArgs paintEvnt) / Get the graphics object Graphics gfx = paintEvnt.Graphics; int x1 = 0; int y1 = 0; / Loop trough the 255 values red can have for (int i = 0; i = 255; i+) / 指定画刷颜色 Color brushColor = Color.FromArgb(i, 0, 0); / 实心画刷用来画实心矩形 SolidBrush myBrush = new SolidBrush(brushColor); / 绘制 gfx.FillRectangle(myBrush, x1, y1, 10, 10); / 挨着画下一个矩形 x1 = x1 + 10; /当一行结束后,画下一行 if (x1 % 290) = 0) y1 = y1 + 10; x1 = 0; for (int i = 0; i = 255; i+) Color brushColor = Color.FromArgb(0, i, 0); SolidBrush myBrush = new SolidBrush(brushColor); gfx.FillRectangle(myBrush, x1, y1, 10, 10); x1 = x1 + 10; if (x1 % 290) = 0) y1 = y1 + 10; x1 = 0; for (int i = 0; i = 255; i+) Color brushColor = Color.FromArgb(0, 0, i); SolidBrush myBrush = new SolidBrush(brushColor); gfx.FillRectangle(myBrush, x1, y1, 10, 10); x1 = x1 + 10; if (x1 % 290) = 0) y1 = y1 + 10; x1 = 0; 分类: C#图形编程1 显示图片主要命令:Image.FromFile();graphics.DrawImage(image);CodeprotectedoverridevoidOnPaint(PaintEventArgspaintEvnt)ImagenewImage=Image.FromFile(C:/test.jpg);/设置图像显示的左上角PointFulCorner=newPointF(10.0F,10.0F);/显示出图片.paintEvnt.Graphics.DrawImage(newImage,ulCorner);
展开阅读全文
相关资源
相关搜索

最新文档


当前位置:首页 > 图纸专区 > 大学资料


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!