NEWS

[C#] Chia sẻ source code Orange Rain in Winform

[C#] Chia sẻ source code Orange Rain in Winform
Đăng bởi: Thảo Meo - Lượt xem: 1724 08:03:47, 27/12/2022C#   In bài viết

Xin chào các bạn, bài viết hôm nay mình chia sẻ các bạn source code tạo Orange Rain trên Background Winform C#, các bạn có thể tìm thêm hiệu ứng tuyết rơi ở bài đọc cũ.

[C#] Source code Orange Rain in winform

Giao diện demo ứng dụng:

purple_rain_csharp

Ở bài viết này, chúng ta sẻ sử dụng 1 timer, các bạn có thể chỉnh tốc độ rơi và chiều dài của Rain.

Source code c#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PurpleRain
{
    public partial class Form1 : Form
    {
        List<Drop> rain = new List<Drop>(); // keeps all drops in one place
        Random rnd = new Random();          // for generating random numbers

        public Form1()
        {
            InitializeComponent();
            for (int i = 0; i < 100; i++) // creates 100 drops at random position and with random speed
                rain.Add(CreateRandomDrop());
        }
        private Drop CreateRandomDrop()
        {
            return new Drop // create drop with random position and speed
            {
                Position = new PointF(rnd.Next(this.Width), rnd.Next(this.Height)),
                YSpeed = (float)rnd.NextDouble() * 3 + 5 // 2..5
            };
        }


        private void UpdateRain() // changes Y position for each drop (falling), also checks if a drop is outside Main form, if yes, resets position to 0
        {
            foreach (var drop in rain)
            {
                drop.Fall();

                if (drop.Position.Y > this.Height)
                    drop.Position.Y = 0;
            }
        }


        private void RenderRain()
        {
            using (var grp = this.CreateGraphics()) // using will call IDisposable.Dispose
            {
                grp.Clear(Color.DarkOrange);

                foreach (var drop in rain)
                    grp.DrawLine(Pens.White, drop.Position, new PointF(drop.Position.X , drop.Position.Y + 5));
            }
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            UpdateRain();
            RenderRain();
        }

        class Drop
        {
            public PointF Position;
            public float YSpeed;

            public void Fall() => Position.Y += YSpeed;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }
    }

   


}

Thanks for watching!

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Chia sẻ source code Orange Rain in Winform
Đăng bởi: Thảo Meo - Lượt xem: 1724 08:03:47, 27/12/2022C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.