C# GDI在控件上绘图的方法
本文以在chart控件上和窗体上画矩形为例子讲述了C#GDI在控件上绘图的方法。分享给大家供大家参考。具体方法如下:
具体的实现方法就不多解释了,备注很详细,代码也很简单。
主要功能代码如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.IO; usingSystem.Configuration; namespaceWFApp2 { publicpartialclassdata:Form { publicdata() { InitializeComponent(); //窗体 g=this.CreateGraphics(); //chart控件 g2=this.chart1.CreateGraphics(); } publicPointfirstPoint=newPoint(0,0);//鼠标第一点 publicPointsecondPoint=newPoint(0,0);//鼠标第二点 publicboolbegin=false;//是否开始画矩形 ///<summary> ///在from上画矩形 ///</summary> Graphicsg; ///<summary> ///在chart1控件上画矩形 ///</summary> Graphicsg2; ///<summary> ///在窗体上按下鼠标事件 ///</summary> ///<paramname="sender"></param> ///<paramname="e"></param> privatevoiddata_MouseDown(objectsender,MouseEventArgse) { begin=true; firstPoint=newPoint(e.X,e.Y); } ///<summary> ///在窗体上鼠标移动开始绘图 ///</summary> ///<paramname="sender"></param> ///<paramname="e"></param> privatevoiddata_MouseMove(objectsender,MouseEventArgse) { if(begin) { //清除窗体绘图面,相当于刷新了一次窗体界面然后重新绘制 g.Clear(this.BackColor); //获取新的右下角坐标 secondPoint=newPoint(e.X,e.Y); //获取两个数中的大者或小者 intminX=Math.Min(firstPoint.X,secondPoint.X); intminY=Math.Min(firstPoint.Y,secondPoint.Y); intmaxX=Math.Max(firstPoint.X,secondPoint.X); intmaxY=Math.Max(firstPoint.Y,secondPoint.Y); //画框 g.DrawRectangle(newPen(Color.Red),minX,minY,maxX-minX,maxY-minY); //ControlPaint.DrawReversibleFrame(newRectangle(minX,minY,maxX-minX,maxY-minY),this.BackColor,FrameStyle.Dashed); } } ///<summary> ///鼠标松开停止绘图 ///</summary> ///<paramname="sender"></param> ///<paramname="e"></param> privatevoiddata_MouseUp(objectsender,MouseEventArgse) { begin=false; } ///<summary> ///在chart控件上移动鼠标绘图 ///</summary> ///<paramname="sender"></param> ///<paramname="e"></param> privatevoidchart1_MouseMove(objectsender,MouseEventArgse) { if(begin) { //重新在chart上面绘图,此处不能用clear方法,clear会清除整个绘图界面chart控件会被清除 this.Refresh(); //获取新的右下角坐标 secondPoint=newPoint(e.X,e.Y); intminX=Math.Min(firstPoint.X,secondPoint.X); intminY=Math.Min(firstPoint.Y,secondPoint.Y); intmaxX=Math.Max(firstPoint.X,secondPoint.X); intmaxY=Math.Max(firstPoint.Y,secondPoint.Y); //画矩形 g2.DrawRectangle(newPen(Color.Red),minX,minY,maxX-minX,maxY-minY); } } ///<summary> ///鼠标松开停止绘图 ///</summary> ///<paramname="sender"></param> ///<paramname="e"></param> privatevoidchart1_MouseUp(objectsender,MouseEventArgse) { begin=false; } ///<summary> ///在chart控件上按下鼠标 ///</summary> ///<paramname="sender"></param> ///<paramname="e"></param> privatevoidchart1_MouseDown(objectsender,MouseEventArgse) { begin=true; firstPoint=newPoint(e.X,e.Y); } } }
希望本文所述对大家的C#程序设计有所帮助