(1)为Form1类增加几个变量
private System.Drawing.Point EndPoint;
private System.Drawing.Point StartPoint;
private System.Drawing.Bitmap bits;
private System.Drawing.Graphics bitG;
private bool flag = false;
(2)在构造函数中实例化
bits = new System.Drawing.Bitmap(pictureBox1.Width, pictureBox1.Height);
bitG = System.Drawing.Graphics.FromImage(bits);
bitG.Clear(System.Drawing.Color.White);
this.BackgroundImage = bits; //设置窗体的背景图片为bits
(3) 处理MouseDown,MouseMove,MouseUp事件
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
flag = true;
StartPoint.X = e.X;
StartPoint.Y = e.Y;
EndPoint.X=e.X;
EndPoint.Y=e.Y;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (flag) //绘画状态
{
Rectangle r1 = getDrawRectangle();
r1.Width += 2;
r1.Height += 2;
this.Invalidate(r1); //前一个区域无效
//相当于是bits图像中保存了所有被记录的绘制内容,所以零时的更新都在窗体上。
this.Update();
EndPoint.X = e.X;
EndPoint.Y = e.Y;
r1 = getDrawRectangle();
this.CreateGraphics().DrawEllipse(Pens.Blue, r1);
}
}
private Rectangle getDrawRectangle()
{
int x1, x2, y1, y2;
if (StartPoint.X < EndPoint.X)
{
x1 = StartPoint.X;
x2 = EndPoint.X;
}
else
{
x1 = EndPoint.X;
x2 = EndPoint.X;
}
if (StartPoint.Y < EndPoint.Y)
{
y1 = StartPoint.Y;
y2 = EndPoint.Y;
}
else
{
y1 = EndPoint.Y;
y2 = StartPoint.Y;
}
return new Rectangle(x1, y1, x2-x1, y2-y1);
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
if (flag)
{
//绘制到bitmap
EndPoint.X = e.X;
EndPoint.Y = e.Y;
Rectangle r=getDrawRectangle();
bitG.DrawEllipse (Pens.Blue, r);
flag = false;
this.BackgroundImage = bits;
}
}
能够解决窗体自动重绘的问题,但是画面有闪烁。本例子参考了《C#应用程序设计教程》。
首发:http://www.iwebtrados.com.cn/post/42.html