溫馨提示×

C#中如何實現(xiàn)優(yōu)雅的Loading效果

c#
小樊
86
2024-08-29 04:29:45
欄目: 編程語言

在C#中,實現(xiàn)優(yōu)雅的加載效果通常需要使用多線程和異步編程。這里有一個簡單的示例,展示了如何在Windows Forms應(yīng)用程序中實現(xiàn)一個優(yōu)雅的加載效果:

  1. 首先,確保你已經(jīng)安裝了.NET Framework 4.5或更高版本。

  2. 創(chuàng)建一個新的Windows Forms應(yīng)用程序項目。

  3. 在解決方案資源管理器中,右鍵單擊項目并選擇“添加”->“用戶控件”。將新的用戶控件命名為“LoadingControl”。

  4. 打開“LoadingControl.cs”文件,然后添加以下代碼:

using System;
using System.Drawing;
using System.Windows.Forms;

public partial class LoadingControl : UserControl
{
    private Timer timer;
    private int angle = 0;

    public LoadingControl()
    {
        InitializeComponent();
        this.DoubleBuffered = true;
        timer = new Timer();
        timer.Interval = 1000 / 60; // 60幀/秒
        timer.Tick += Timer_Tick;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        DrawLoadingCircle(e.Graphics);
    }

    private void DrawLoadingCircle(Graphics g)
    {
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        float radius = Math.Min(this.Width, this.Height) / 2 - 5;
        RectangleF rect = new RectangleF(this.Width / 2 - radius, this.Height / 2 - radius, radius * 2, radius * 2);
        using (SolidBrush brush = new SolidBrush(Color.FromArgb(128, Color.Blue)))
        {
            g.FillPie(brush, rect, angle, 90);
        }
    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        angle = (angle + 30) % 360;
        this.Invalidate();
    }

    public void Start()
    {
        timer.Start();
    }

    public void Stop()
    {
        timer.Stop();
    }
}
  1. 在主窗體(例如“Form1.cs”)中,將“LoadingControl”添加到窗體上。你可以通過將其從工具箱拖放到窗體上來實現(xiàn)這一點。

  2. 在主窗體的“Load”事件中,調(diào)用“l(fā)oadingControl1.Start()”以啟動加載動畫。當(dāng)加載完成時,調(diào)用“l(fā)oadingControl1.Stop()”以停止動畫。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.Load += Form1_Load;
    }

    private async void Form1_Load(object sender, EventArgs e)
    {
        loadingControl1.Start();
        await Task.Delay(3000); // 模擬加載過程
        loadingControl1.Stop();
    }
}

現(xiàn)在,當(dāng)你運(yùn)行應(yīng)用程序時,你應(yīng)該會看到一個優(yōu)雅的加載效果。這個示例使用了一個簡單的旋轉(zhuǎn)圓圈,但你可以根據(jù)需要自定義加載動畫。

0