四行代码教你实现C#气泡反弹

一.编程思想

(1).反弹肯定需要时间间隔,需要timer计时器来完成
(2).反弹时需要条件判断,所以需要if语句
(3).气泡都是圆的,我们需要进行实例化

二.代码实现

(1).简单的对窗体进行设置
            this.Location = new Point(0,0);//设置窗体位置
            this.FormBorderStyle = FormBorderStyle.None;//设置窗体无边框
            this.Size = new Size(200,200);//设置窗体大小
            this.Opacity = 0.4;//设置不透明度
            this.BackColor = Color.Blue;//设置背景颜色
(2).对气泡进行画圆
 //将窗体画成圆形,实例化
            GraphicsPath path = new GraphicsPath();
            path.AddEllipse(0,0,this.Width,this.Height);
            this.Region = new Region(path);
(3).if语句的判断条件
            if (this.Top+this.Height>=Screen.PrimaryScreen.Bounds.Height||this.Top<=0)//判断窗体高度加上上边缘高度与桌面高度
            {
                y = -y;
            }
            if (this.Left+this.Width>=Screen.PrimaryScreen.Bounds.Width||this.Left<=0)//判断窗体宽度加上左边缘高度与桌面宽度
            {
                x = -x;
            }
(4).整体代码的实现
private void 气泡案例_Load(object sender, EventArgs e)
        {
            this.Location = new Point(0,0);//设置窗体位置
            this.FormBorderStyle = FormBorderStyle.None;//设置窗体无边框
            this.Size = new Size(200,200);//设置窗体大小
            this.Opacity = 0.4;//设置不透明度
            this.BackColor = Color.Blue;//设置背景颜色
            //将窗体画成圆形,实例化
            GraphicsPath path = new GraphicsPath();
            path.AddEllipse(0,0,this.Width,this.Height);
            this.Region = new Region(path);
            timer1.Start();//开启计时器
        }
        int x = 5;
        int y = 8;
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Top += y;
            this.Left += x;
            if (this.Top+this.Height>=Screen.PrimaryScreen.Bounds.Height||this.Top<=0)//判断窗体高度加上上边缘高度与桌面高度
            {
                y = -y;
            }
            if (this.Left+this.Width>=Screen.PrimaryScreen.Bounds.Width||this.Left<=0)//判断窗体宽度加上左边缘高度与桌面宽度
            {
                x = -x;
            }
        }

一个计时器四行代码气泡的反弹就完成了

在这里插入图片描述

原创文章 36 获赞 31 访问量 2088

猜你喜欢

转载自blog.csdn.net/qq_45096273/article/details/105464245