四行代碼教你實現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;
            }
        }

一個計時器四行代碼氣泡的反彈就完成了

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章