zoukankan      html  css  js  c++  java
  • c#GDI+实现用鼠标画矩形

    c#GDI+实现用鼠标画矩形

    2018年05月25日 16:52:40 头发日渐减少 阅读数 954

    要求:

    设计一个根据鼠标来绘制矩形框的程序,即当按下鼠标左键并拖动至某个位置后释放鼠标使,可根据按下鼠标时的第一个点和释放鼠标时的第二个点来确定并绘制该矩形。

    设计思路:

    1.首先得到首次鼠标点击的位置 ,然后再得到鼠标在最后得到的位置。

    2.我们就需要返回值得到(x2-x1)的值,还有(y2-y1)的值

    3.我们在后台调动GDI+,将图像画出来。

    实现步骤。

    1.首先用鼠标的事件MouseDown、MouseUp得到鼠标点击时和鼠标松开时的x和y的坐标位置。具体的代码如下:

     private void form1_MouseDown(object sender, MouseEventArgs e)
            {
                firstpoint.X = e.X;
                firstpoint.Y = e.Y;
            }


            private void form1_MouseUp(object sender, MouseEventArgs e)
            {
                secondpoint.X = e.X;
                secondpoint.Y = e.Y;
               

            }

    当然在这之前要先定义fristpoint和second,如下:

    Point firstpoint;

     Point secondpoint;

    2.定义一个画图工具

    Graphics gra;

    3.确定矩形的位置

     gra.DrawRectangle(drawPen, firstpoint.X, firstpoint.Y, secondpoint.X - firstpoint.X, secondpoint.Y - firstpoint.Y);

    4.下面附上全部的代码和截图效果:

     Graphics gra;
            Point firstpoint;
            Point secondpoint;
            public form1()
            {
                InitializeComponent();
                gra = this.CreateGraphics();
                firstpoint = new Point(0, 0);
                secondpoint = new Point(0, 0);


            }
       


            private void Form1_Paint(object sender, PaintEventArgs e)
            {
           
            }


            private void form1_MouseDown(object sender, MouseEventArgs e)
            {
                firstpoint.X = e.X;
                firstpoint.Y = e.Y;
            }


            private void form1_MouseUp(object sender, MouseEventArgs e)
            {
                secondpoint.X = e.X;
                secondpoint.Y = e.Y;
                Pen drawPen = new Pen(Color.Red, 3);
                gra.DrawRectangle(drawPen, firstpoint.X, firstpoint.Y, secondpoint.X - firstpoint.X, secondpoint.Y - firstpoint.Y);


            }

     

        }

    写的不好互喷,也希望能够给大家提供下参考。

  • 相关阅读:
    Maximum Flow Exhaustion of Paths Algorithm
    ubuntu下安装java环境
    visualbox使用(二)
    vxworks一个超级奇怪的错误(parse error before `char')
    February 4th, 2018 Week 6th Sunday
    February 3rd, 2018 Week 5th Saturday
    February 2nd, 2018 Week 5th Friday
    February 1st, 2018 Week 5th Thursday
    January 31st, 2018 Week 05th Wednesday
    January 30th, 2018 Week 05th Tuesday
  • 原文地址:https://www.cnblogs.com/grj001/p/12224550.html
Copyright © 2011-2022 走看看