这是本人第一次在blog上发一个小代码,水平有限,慢慢努力
这是用C#编写的关于用鼠标绘图代码,代码及讲解如下




















//创建缓冲
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
bitmap = new Bitmap(this.pictureBox1.Width,this.pictureBox1.Height);
this.pictureBox1.Image=bitmap;
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

Windows 窗体设计器生成的代码

private void pictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.CanMove=true;
this.startPoint=new Point(e.X,e.Y);
}

private void pictureBox1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(this.CanMove==true)
{
this.pictureBox1.Image=(Bitmap)this.bitmap.Clone();
using(Graphics graphics = Graphics.FromImage(this.pictureBox1.Image))
{
graphics.Clear(Color.Transparent);//清除
graphics.DrawLine(new Pen(Color.Red,1),this.startPoint,new Point(e.X,e.Y));//重绘
graphics.DrawImage(this.bitmap,this.pictureBox1.Location.X,this.pictureBox1.Location.Y,this.pictureBox1.Width,this.pictureBox1.Height);
}
}
}

private void pictureBox1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.pictureBox1.Image = this.bitmap;
using(Graphics graphics = Graphics.FromImage(this.pictureBox1.Image))
{
graphics.DrawLine(new Pen(Color.Red,1),this.startPoint,new Point(e.X,e.Y));
}
this.CanMove=false;
}
}
}





















































参考:
http://www.codeproject.com/dotnet/rubberbandline.asp