zoukankan      html  css  js  c++  java
  • C#矩形框沿直线移动

    C#中用GDT+的一系列方式,可以绘制各种图形:点,直线,圆形,矩形......

    C#中这些图形的绘制,一般教程的demo中给出的代码,是在Form1_Paint(object sender, PaintEventArgs e)函数中完成绘图。这个函数是窗口一出来就调用。

    如果我希望GUI界面上某个事件发生后再绘图(而不是窗口一上来就绘制),那就在对应的事件处理函数中调用绘图的函数代码。一般的事件处理函数不带PaintEventArgs参数,通过定义Graphics类型的全局变量g并调用窗体的CreateGraphics函数来解决。

    下面给出一个简单的例子:一个简单窗体,界面上只有一个按钮btn,点击btn会在窗口指定位置产生一个绿色矩形框,并向右移动一定距离。
    通过前述方式+timer控件,可以实现这个操作,代码如下:

        public partial class Form1 : Form {
            public Form1() {
                InitializeComponent();
                g = this.CreateGraphics();
                rect = new Rectangle(x, y, width, height);
                timer1.Tick += new System.EventHandler(timer1_Tick);
                timer1.Interval = 100;
            }
            private Timer timer1 = new Timer();
    
            private Pen pen = new Pen(Color.Lime, 2); //绿色画笔
            private Pen DefaultPen = new Pen(Control.DefaultBackColor, 2); //颜色和窗体背景色相同的画笔
    
            int x = 100, y = 100;
            int width = 60, height = 60;
            private Rectangle rect;
    
            private Graphics g;
    
            private void button1_Click(object sender, EventArgs e) {
                //move2right();
                timer1.Enabled = true;
            }
    
            //整个矩形框整体向右移动两个距离
            private void move2right() {
                g.DrawRectangle(DefaultPen, rect);
                rect.X += 2;
                g.DrawRectangle(pen, rect);
                Invalidate(rect);
            }
    
            //计时器,用来让矩形持续移动
            public void timer1_Tick(object sender, EventArgs e) {
                if (rect.X < 410) {
                    move2right();
                }
            }
        }
    

    以上代码通过每次把前面一次绘制的矩形框颜色涂为窗体背景色,然后在新位置绘制新的矩形,缺点是如果窗口中除了矩形框还有别的图形,比如直线,那么这个先前绘制的之间会被擦除。

    Greatness is never a given, it must be earned.
  • 相关阅读:
    LeetCode 461. Hamming Distance
    LeetCode 442. Find All Duplicates in an Array
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode Find the Difference
    LeetCode 415. Add Strings
    LeetCode 445. Add Two Numbers II
    LeetCode 438. Find All Anagrams in a String
    LeetCode 463. Island Perimeter
    LeetCode 362. Design Hit Counter
    LeetCode 359. Logger Rate Limiter
  • 原文地址:https://www.cnblogs.com/zjutzz/p/4439814.html
Copyright © 2011-2022 走看看