GDI+学习(5)用拖动鼠标方法手绘(只实现画椭圆)

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

转载于:https://www.cnblogs.com/webtrados/archive/2009/07/21/1528191.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值