温馨提示×

C#中如何实现优雅的Loading效果

c#
小樊
85
2024-08-29 04:29:45
栏目: 编程语言

在C#中,实现优雅的加载效果通常需要使用多线程和异步编程。这里有一个简单的示例,展示了如何在Windows Forms应用程序中实现一个优雅的加载效果:

  1. 首先,确保你已经安装了.NET Framework 4.5或更高版本。

  2. 创建一个新的Windows Forms应用程序项目。

  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”添加到窗体上。你可以通过将其从工具箱拖放到窗体上来实现这一点。

  2. 在主窗体的“Load”事件中,调用“loadingControl1.Start()”以启动加载动画。当加载完成时,调用“loadingControl1.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();
    }
}

现在,当你运行应用程序时,你应该会看到一个优雅的加载效果。这个示例使用了一个简单的旋转圆圈,但你可以根据需要自定义加载动画。

0