c#

利用C#实现自定义Loading图标

小樊
84
2024-08-29 04:33:41
栏目: 编程语言

在C#中,你可以使用Windows Forms或WPF来创建一个自定义的Loading图标。这里我将为你提供一个简单的Windows Forms示例。首先,你需要创建一个新的Windows Forms项目。

  1. 打开Visual Studio,创建一个新的Windows Forms应用程序项目(File > New > Project > Windows Forms App (.NET))并命名为"CustomLoadingIcon"。

  2. 在解决方案资源管理器中,双击"Form1.cs"以打开设计器。

  3. 从工具箱中,将一个"PictureBox"控件拖放到表单上。将其位置设置为(100, 100),大小设置为(100, 100)。

  4. 选中"PictureBox"控件,然后在属性窗口中,将"Modifiers"属性设置为"Public"。

  5. 双击表单以打开"Form1.cs"的代码视图。在"Form1"类中添加以下代码:

using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CustomLoadingIcon
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            await Task.Run(() => StartLoadingAnimation());
        }

        private void StartLoadingAnimation()
        {
            int degree = 0;
            while (true)
            {
                degree = (degree + 10) % 360;
                this.Invoke((Action)(() =>
                {
                    pictureBox1.Image = GenerateRotatedImage("loading.png", degree);
                }));
                System.Threading.Thread.Sleep(50);
            }
        }

        private Image GenerateRotatedImage(string imagePath, int degree)
        {
            Image originalImage = Image.FromFile(imagePath);
            Bitmap rotatedImage = new Bitmap(originalImage.Width, originalImage.Height);
            using (Graphics g = Graphics.FromImage(rotatedImage))
            {
                g.TranslateTransform(originalImage.Width / 2, originalImage.Height / 2);
                g.RotateTransform(degree);
                g.TranslateTransform(-originalImage.Width / 2, -originalImage.Height / 2);
                g.DrawImage(originalImage, new Point(0, 0));
            }
            return rotatedImage;
        }
    }
}
  1. 将一个名为"loading.png"的图像文件添加到项目中(右键项目 > Add > Existing Item)。确保将其复制到输出目录(在属性窗口中,将"Copy to Output Directory"设置为"Copy always")。

  2. 运行项目,你将看到一个旋转的Loading图标。

这个示例中,我们创建了一个PictureBox控件,并在表单加载时启动了一个异步任务来旋转图像。GenerateRotatedImage函数根据给定的角度生成一个旋转后的图像。你可以根据需要修改这个示例,例如更改图像文件、旋转速度等。

0
看了该问题的人还看了