码迷,mamicode.com
首页 > Windows程序 > 详细

C#窗体上绘制矩形

时间:2015-11-20 06:58:27      阅读:353      评论:0      收藏:0      [点我收藏+]

标签:

先上效果图

 

技术分享

 

 

鼠标三个事件

 

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写出来的应该是不会闪烁的

 

C#窗体上绘制矩形

标签:

原文地址:http://www.cnblogs.com/magicianlyx/p/4979644.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!