C#窗体上绘制矩形

先上效果图

 

 

 

鼠标三个事件

 

private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            //记录开始点
            this.mousedown = true;
            this.startpoint = e.Location;

        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            //记录结束点。绘制到窗口上
            if (mousedown)
            {
                this.endpoint = e.Location;
                this.Refresh();
                gform.DrawImage(this.bmsave, new Point(0, 0));
                Rectangle rect = new Rectangle();
                this.rect_play(ref rect);

                gform.DrawRectangle(new Pen(Color.Black), rect);
            }
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            //记录结束点。绘制到bitmap上
            this.endpoint = e.Location;
            this.mousedown = false;
            Rectangle rect = new Rectangle();
            this.rect_play(ref rect);
            g.DrawRectangle(new Pen(Color.Black), rect);
            gform.DrawImage(this.bmsave, new Point(0, 0));
        }

 

 

 

根据startpoint和endpoint两个点去确定要画的矩形Location和width,heigth

 

        private void rect_play( ref Rectangle rect)
        {
            //根据两个点确定矩形的左上角点Location
            if (this.startpoint.X > this.endpoint.X && this.startpoint.Y < this.endpoint.Y)
            {
                rect.Location = new Point(this.endpoint.X, this.startpoint.Y);
            }
            else if (this.startpoint.X < this.endpoint.X && this.startpoint.Y > this.endpoint.Y)
            {
                rect.Location = new Point(this.startpoint.X, this.endpoint.Y);

            }
            else if (this.startpoint.X > this.endpoint.X && this.startpoint.Y > this.endpoint.Y)
            {
                rect.Location = this.endpoint;
            }
            else
            {
                rect.Location = this.startpoint;
            }
            //获取两点的X,Y距离
            rect.Width = Math.Abs(this.startpoint.X - this.endpoint.X);
            rect.Height = Math.Abs(this.startpoint.Y - this.endpoint.Y);

            
            if (rect.Width == 0 && rect.Height == 0)
            {
                //防止误点的时候进行绘制
            }
            else if (rect.Width == 0)
            {
                rect.Width = 1;

            }
            else if (rect.Height == 0)
            {
                rect.Height = 1;
            }
        }

 

 

完整实例代码链接:http://pan.baidu.com/s/1sjkpic1

 

画的时候窗口闪的特别厉害啊,因为大量的Refresh和Draw,开双缓冲也不起多大作用

迟点有时间用QT c++做一个,QT写出来的应该是不会闪烁的

如果哪位前辈有能解决闪烁问题的,希望在评论区留言,感激不尽

 


 

补:http://www.cnblogs.com/magicianlyx/p/4987169.html 这个是QT版本的,不会闪烁

 

转载于:https://www.cnblogs.com/magicianlyx/p/4979644.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值