Анимация в windows form c

Introduction

In this article, we will learn how to create an animated loading screen in windows form application. We can also say that animation is a picture or figure which are manipulated to appear as moving images. This will help us to create animated windows forms. adding animation in forms will make it different from other simple forms. Let’s have a look at the steps for the animated screen in windows forms application.

Step 1

First of all open visual studio and then click on create new project.

Adding Animated screen using windows forms

Step 2 

After clicking create a new project, a new window will pop up in this new window you have to click on windows form application and it will help to select the templates of the project and then click on next button.

Adding Animated screen using windows forms

Step 3 

In this step you have to select the name of the project, location of the project, and the .Net framework of your choice after that click on create.

Adding Animated screen using windows forms

Step 4

After selecting the name of the project similar window will pop up as shown below and then click on solution explorer then right-click on the name that you have decided for the project as I have decided is demo.

Adding Animated screen using windows forms

Step 5

Solution explorer will open the given below menu in the menu you have to select add menu and in add menu select new item.   

   

Step 6

In this window, Select User Control(Windows Forms) option and in name section you can change the name after that click on add button.

Adding Animated screen using windows forms

Step 7

After clicking add button a new window will open in this window you have to double click and then given below window will pop up.

Adding Animated screen using windows forms

Step 8

And then write the code for creating animated screen and it contains color of the screen, size of the screen, and border radius. For creating a rectangle you have to add a namespace called system.Drawing.Drawing2D. after that write given below code.

protected override void OnPaint(PaintEventArgs e) {
    e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
    GraphicsPath gp = new GraphicsPath();
    gp.AddArc(new Rectangle(0, 0, size, size), 180, 90);
    gp.AddArc(new Rectangle(Width - size, 0, size, size), -90, 90);
    gp.AddArc(new Rectangle(Width - size, Height - size, size, size), 0, 90);
    gp.AddArc(new Rectangle(0, Height - size, size, size), 90, 90);
    e.Graphics.FillPath(new LinearGradientBrush(ClientRectangle, clor1, clor2, distance), gp);
    e.Graphics.DrawString(txt, Font, new SolidBrush(ForeColor), ClientRectangle, new StringFormat() {
        LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center
    });
    base.OnPaint(e);
}

gp.AddArc will create a curve rectangle and e.graphics.fillpath will add colors to curved rectangle and in last e.graphics.drawstring will add text to the screen, 

Step 9

Next add the colors to the screen for that create property in this get method return the value of the variable name and set method will assign the value.

public Color Color {
    get {
        return clor1;
    }
    set {
        clor1 = value;
        Invalidate();
    }
}
public Color Color1 {
    get {
        return clor2;
    }
    set {
        clor2 = value;
        Invalidate();
    }
}

In above code get method will return the value of clor1 and set method will assign the value of clor1. Similarly, in Color1 get method will return the value of clor2 and set method will assign the value of clor2.  

Step 10

public UserControl1() {
    InitializeComponent();
    DoubleBuffered = true;
    t.Interval = 60;
    t.Start();
    t.Tick += (s, e) => {
        angle = angle % 360 + 1;
    };
    ForeColor = Color.White;
}
public float angle {
    get {
        return distance;
    }
    set {
        distance = value;
        Invalidate();
    }
}
public int Borderradius {
    get {
        return size;
    }
    set {
        size = value;
        Invalidate();
    }
}

In this create an object of timer called t and above code is used to start the timer, interval, and tick (occurs when intervals have elapsed). And to create borderradius in the get method will return the size of the radius and set method will assign the size of the screen.

using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace animation {
    [DefaultEvent("click")]
    public partial class UserControl1: UserControl {
        int size = 20;
        float distance = 45;
        Color clor1 = Color.Blue, clor2 = Color.Orange;
        Timer t = new Timer();
        string txt = "Loading";
        public UserControl1() {
            InitializeComponent();
            DoubleBuffered = true;
            t.Interval = 60;
            t.Start();
            t.Tick += (s, e) => {
                angle = angle % 360 + 1;
            };
            ForeColor = Color.White;
        }
        public float angle {
            get {
                return distance;
            }
            set {
                distance = value;
                Invalidate();
            }
        }
        public int Borderradius {
            get {
                return size;
            }
            set {
                size = value;
                Invalidate();
            }
        }
        protected override void OnPaint(PaintEventArgs e) {
            e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
            GraphicsPath gp = new GraphicsPath();
            gp.AddArc(new Rectangle(0, 0, size, size), 180, 90);
            gp.AddArc(new Rectangle(Width - size, 0, size, size), -90, 90);
            gp.AddArc(new Rectangle(Width - size, Height - size, size, size), 0, 90);
            gp.AddArc(new Rectangle(0, Height - size, size, size), 90, 90);
            e.Graphics.FillPath(new LinearGradientBrush(ClientRectangle, clor1, clor2, distance), gp);
            e.Graphics.DrawString(txt, Font, new SolidBrush(ForeColor), ClientRectangle, new StringFormat() {
                LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center
            });
            base.OnPaint(e);
        }
        public Color Color {
            get {
                return clor1;
            }
            set {
                clor1 = value;
                Invalidate();
            }
        }
        public Color Color1 {
            get {
                return clor2;
            }
            set {
                clor2 = value;
                Invalidate();
            }
        }
        private void UserControl1_Load(object sender, EventArgs e) {}
    }
}

Conclusion

This article will help to create an animated screen using windows forms appliction in c#. This is all about creating animated forms different from other simple forms.

Thanks, I hope this will help you.

  • Subject:
    C# Tutorials
  • Learning Time: 1 hour

Lets make something fun. How about a simple animation where you get to animate a single character walking around the screen in all 4 directions and we will get to do this only using C# and Visual Studio. Well it can sound sort of confusing at first but we have figured out how to do this in style. In this tutorial you will find the answers to all of those questions. We will break down how to make a simple animation only using C# and we will be importing out images and loading them inside of the program and animate them using a custom function. This type of animation is very popular for Zelda games and some top down isometric games. We will recreate just the movement and demonstrate it using windows forms and visual studio. Lets get started.

Lesson objectives –

  1. Create a 4 way movement animation using sprites and c# programming
  2. Load player movements from a folder and save them to a list
  3. use the list to display specific images when a specific movement is triggered in the program
  4. Use arrow keys to move the player object
  5. Use paint and timer event to move and animate the player object
  6. Create custom functions to limit the movements and show only the corresponding images as animations
  7. Slow down the animation to make it looks more suitable for the application

Video Tutorial –

Download Images and Background here

Get C# 4 Way Movement and Item Pick Up Project on GitHub

Once you’ve completed this tutorial, you can do the part 2 of this tutorial on How to Randomly Spawn Items and Pick them up in the game.

Source Code –

namespace _4_Way_Movement_with_Sprite_Images_MOO_ICT
{
    public partial class Form1 : Form
    {
        // created by mooict.com
        // for educational purpose only
        Image player;
        List playerMovements = new List();
        int steps = 0;
        int slowDownFrameRate = 0;
        bool goLeft, goRight, goUp, goDown;
        int playerX;
        int playerY;
        int playerHeight = 100;
        int playerWidth = 100;
        int playerSpeed = 8;
        public Form1()
        {
            InitializeComponent();
            SetUp();
        }
        private void KeyIsDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Left)
            {
                goLeft = true;
            }
            if (e.KeyCode == Keys.Right)
            {
                goRight = true;
            }
            if (e.KeyCode == Keys.Up)
            {
                goUp = true;
            }
            if (e.KeyCode == Keys.Down)
            {
                goDown = true;
            }
        }
        private void KeyIsUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Left)
            {
                goLeft = false;
            }
            if (e.KeyCode == Keys.Right)
            {
                goRight = false;
            }
            if (e.KeyCode == Keys.Up)
            {
                goUp = false;
            }
            if (e.KeyCode == Keys.Down)
            {
                goDown = false;
            }
        }
        private void FormPaintEvent(object sender, PaintEventArgs e)
        {
            Graphics Canvas = e.Graphics;
            Canvas.DrawImage(player, playerX, playerY, playerWidth, playerHeight);  
        }
        private void TimerEvent(object sender, EventArgs e)
        {
            if (goLeft && playerX > 0)
            {
                playerX -= playerSpeed;
                AnimatePlayer(4, 7);
            }
            else if (goRight && playerX + playerWidth < this.ClientSize.Width)  
            { 
               playerX += playerSpeed; 
               AnimatePlayer(8, 11); 
            } 
            else if (goUp && playerY > 0)
            {
                playerY -= playerSpeed;
                AnimatePlayer(12, 15);
            }
            else if (goDown && playerY + playerHeight < this.ClientSize.Height) 
            { 
               playerY += playerSpeed; AnimatePlayer(0, 3); 
            } 
            else 
            { 
               AnimatePlayer(0, 0); 
            } 
            this.Invalidate(); 
            lblMovement.Text = "Movements: " + steps; 
       } 
       private void SetUp() 
            { 
               this.BackgroundImage = Image.FromFile("bg.jpg"); 
               this.BackgroundImageLayout = ImageLayout.Stretch; 
               this.DoubleBuffered = true; 
               // load the player files to the list 
               playerMovements = Directory.GetFiles("player", "*.png").ToList(); 
               player = Image.FromFile(playerMovements[0]); 
       } 
      private void AnimatePlayer(int start, int end) 
            { 
               slowDownFrameRate += 1; 
             if (slowDownFrameRate == 4) 
             { 
                steps++; 
                slowDownFrameRate = 0; 
             } 
             if (steps > end || steps < start)
            {
                steps = start;
            }
            player = Image.FromFile(playerMovements[steps]);
      }
    }
}

0 / 0 / 0

Регистрация: 27.11.2013

Сообщений: 9

1

Анимация движения

14.05.2014, 19:34. Показов 28277. Ответов 7


Студворк — интернет-сервис помощи студентам

Подскажите, как создать анимацию движущегося человечка на Windows Forms без OpenGL и прочего



0



evgeniy-tlt

2 / 2 / 2

Регистрация: 09.05.2014

Сообщений: 12

15.05.2014, 14:51

2

По-очереди картинку вставлять в pictureBox. Вот рабочий пример (через потоки).

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Text;
using System.Windows.Forms;
 
namespace Form_Thread_Animation
{
    public partial class Form1 : Form
    {
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e) { }
 
        public void updateBox()
        {
            for (int i = 1; i <= 10; i++)
            {
                this.Invoke((MethodInvoker)delegate()
                {
                    pictureBox1.ImageLocation = "C:\\" + i.ToString()+".jpg";
                }
                );
                Thread.Sleep(100);
                if (i==10) i=0;
            };
 
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(updateBox));
            thread.IsBackground = true;
            thread.Start();
        }
 
    }
}



0



Siroga00VII

0 / 0 / 1

Регистрация: 13.08.2016

Сообщений: 26

01.08.2017, 22:39

3

Упростим

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Text;
using System.Windows.Forms;
 
namespace Form_Thread_Animation
{
    public partial class Form1 : Form
    {
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e) { }
 
        public void updateBox()
        {
            for (int i = 1; i <= 10; i++)
            {
                this.Invoke((MethodInvoker)delegate()
                {
                    pictureBox1.ImageLocation = $"C:\\{i.ToString()}.jpg";
                }
                );
                Thread.Sleep(100);
                if (i==10) i=0;
            };
 
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
           Task.Run(()=>updateBox());
        }
 
    }
}



0



309 / 317 / 119

Регистрация: 29.10.2011

Сообщений: 1,006

02.08.2017, 11:23

4

Nikovsky, Посмотрите, как это сделано, например, в XNA(на ютубе много видео). И попробуйте повторить. Да, некоторые классы придётся реализовать самому, но в главное вы поймете сам подход. И обойдете стороной примеры выше.



0



TheGreatCornholio

1250 / 728 / 285

Регистрация: 30.07.2015

Сообщений: 2,407

02.08.2017, 12:45

5

Цитата
Сообщение от Nikovsky
Посмотреть сообщение

Подскажите, как создать анимацию движущегося человечка на Windows Forms без OpenGL и прочего

Очевидно через GDI, GDI+, которые собственно использует WinForms.
Предлагаю почерпнуть вдохновения отсюда



0



84 / 85 / 48

Регистрация: 12.10.2013

Сообщений: 1,079

04.08.2017, 22:11

6

GO!!!



1



Веселый

84 / 85 / 48

Регистрация: 12.10.2013

Сообщений: 1,079

04.08.2017, 22:20

7

Код простота!!! Можете совершенствовать бесконечно.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Media;
using System.IO;
 
 
namespace AnimationTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
           // var objSP = new SoundPlayer(AnimationTest.Properties.Resources.Muzyka_na_telefon___Rzhanie_loshadi_Pesni_Tut);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            var objSP1 = new SoundPlayer(AnimationTest.Properties.Resources.loshadi_topot_kopyt);
            objSP1.PlayLooping();
            timer1.Start();
        }
      
        int w = 0;
        int r = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            ++w;
            r -= 18;
            pictureBox1.Location = new Point(r + 700, pictureBox1.Location.Y);
     
            if (w == 1)
            {
                pictureBox1.Image = new Bitmap(AnimationTest.Properties.Resources._1);
            }
            if (w == 3)
            {
                pictureBox1.Image = new Bitmap(AnimationTest.Properties.Resources._2);
            }
            if (w == 4)
            {
                pictureBox1.Image = new Bitmap(AnimationTest.Properties.Resources._3);
            }
            if (w == 6)
            {
                pictureBox1.Image = new Bitmap(AnimationTest.Properties.Resources._4);
            }
            if (w == 8)
            {
                pictureBox1.Image = new Bitmap(AnimationTest.Properties.Resources._5);
            }
            if (w == 10)
            {
                pictureBox1.Image = new Bitmap(AnimationTest.Properties.Resources._6);
            }
            if (w == 10)
            {
                w = 0;
            }
            if (r == -770)// Это  работает !!!
            {
                //var objSP = new SoundPlayer(AnimationTest.Properties.Resources.Muzyka_na_telefon___Rzhanie_loshadi_Pesni_Tut);
                //objSP.Play();
                r = 0;
                r -= 14;
                pictureBox1.Location = new Point(r + 700, pictureBox1.Location.Y);
            }                 
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            
        }
    }

}



0



0 / 0 / 0

Регистрация: 18.11.2022

Сообщений: 1

18.11.2022, 15:08

8

cпс



0



Я советую использовать класс System.Windows.Forms.Timer для таких целей. Создайте таймер, задайте интервал в миллисекундах через который будет генерироваться событие Tick. Событию присвойте обработчик, в котором накапливайте число шагов (например в статическую переменную). Если оно превысило нужное вам, то останавливайте таймер. Пример кода вам в помощь.

private void mainForm_Click(object sender, EventArgs e)
        {
            Timer timer = new Timer();
            timer.Interval = 30; // каждые 30 миллисекунд
            int count = 0;
            int max = 10;
            Graphics g = this.CreateGraphics();
            g.Clear(Color.White);
            int x = 10;
            int y = 10;
            g.DrawEllipse(Pens.Black, x, y, 10, 10);
            timer.Tick += new EventHandler((o, ev) =>
            {
                x += 5;
                y += 5;
                g.Clear(Color.White);
                g.DrawEllipse(Pens.Black, x, y, 10, 10);
                count++;

                if (count == max)
                {
                    Timer t = o as Timer; // можно тут просто воспользоваться timer
                    t.Stop();
                }
            });
            timer.Start();   // запустили, а остановится он сам                              
        }

Этот код по клику двигает кружок на пустой форме.
Если вы хотите, например, всегда за 1 секунду рисовать анимацию, то соответсвенно берите всегда интервал, скажем, 10 миллисекунд и 100 шагов, а параметры изображения меняйте на 1/100 от общего изменения (разность между началом и концом анимации) за каждый шаг. Можно еще снижать частоту перерисовки для маленьких объектов, но это уже на ваше усмотрение.

Анимация в Windows Forms

Windows Forms — это каркас приложения Windows, который позволяет создавать графические пользовательские интерфейсы для приложений Windows. Одним из базовых элементов Windows Forms является PictureBox, который предназначен для отображения изображений и анимации. В этой статье мы рассмотрим, как создавать анимацию в Windows Forms, используя PictureBox.

Создание анимации в Windows Forms

Загрузить изображения
Первый шаг в создании анимации — это загрузка отдельных кадров анимации в PictureBox. В Windows Forms можно использовать класс Image для загрузки и отображения изображений в PictureBox. Чтобы загрузить изображение в PictureBox, вы можете использовать следующий код:

pictureBox.Image = Image.FromFile(@"C:\animation_frame_1.png");

Для загрузки нескольких кадров анимации вы можете использовать массив Image:

Image[] animationFrames =
{
    Image.FromFile(@"C:\animation_frame_1.png"),
    Image.FromFile(@"C:\animation_frame_2.png"),
    Image.FromFile(@"C:\animation_frame_3.png")
};

Отображение анимации
После загрузки кадров анимации в PictureBox, следующий шаг — это отображение этих кадров в PictureBox с определенной задержкой, чтобы создать эффект анимации. Для этого можно использовать таймер:

private int frameIndex = 0;
private Image[] animationFrames = { Image.FromFile(@"C:\animation_frame_1.png"), Image.FromFile(@"C:\animation_frame_2.png"), Image.FromFile(@"C:\animation_frame_3.png") };

private void timer_Tick(object sender, EventArgs e)
{
    pictureBox.Image = animationFrames[frameIndex];
    frameIndex = (frameIndex + 1) % animationFrames.Length;
}

В этом коде мы используем таймер, чтобы каждые несколько миллисекунд обновлять изображение в PictureBox с новым кадром анимации. Переменная frameIndex используется для отслеживания текущего кадра анимации, а переменная animationFrames хранит все кадры анимации.

Изменение скорости анимации
Если вы хотите изменить скорость анимации, вы можете изменить интервал таймера:

timer.Interval = 50; // Установить интервал в 50 миллисекунд

Чем меньше значение интервала, тем быстрее будет проигрываться анимация.

Остановка и возобновление анимации
Вы также можете остановить и возобновить анимацию в PictureBox при помощи методов Stop() и Start() таймера:

timer.Stop(); // Остановить анимацию
timer.Start(); // Возобновить анимацию

Создание плавной анимации
Чтобы создать плавную анимацию, вы можете использовать эффект сглаживания, чтобы сделать переход между кадрами более плавным. Для этого вы можете использовать класс Bitmap и метод Graphics.DrawImage для наложения кадров анимации друг на друга:

private Bitmap animationBitmap = new Bitmap(800, 600);
private Graphics animationGraphics;
private int frameIndex = 0;
private Image[] animationFrames = { Image.FromFile(@"C:\animation_frame_1.png"), Image.FromFile(@"C:\animation_frame_2.png"), Image.FromFile(@"C:\animation_frame_3.png") };

private void timer_Tick(object sender, EventArgs e)
{
    animationGraphics.DrawImage(animationFrames[frameIndex], 0, 0);
    pictureBox.Image = animationBitmap;
    frameIndex = (frameIndex + 1) % animationFrames.Length;
}

private void Form1_Load(object sender, EventArgs e)
{
    animationGraphics = Graphics.FromImage(animationBitmap);
    animationGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
}

В этом коде мы создаем битмап и графику, чтобы наложить кадры анимации друг на друга с использованием метода DrawImage класса Graphics. Мы также устанавливаем режим сглаживания для графики, чтобы создать эффект более плавной анимации.

Заключение
После прочтения этой статьи вы должны знать, как создавать анимацию в Windows Forms с помощью PictureBox и таймера. Вы также узнали, как изменять скорость анимации, останавливать и возобновлять ее, а также создавать эффект более плавной анимации при помощи класса Bitmap и метода DrawImage класса Graphics.

Надеюсь, эта статья поможет вам создать красивую анимацию для вашего следующего приложения Windows. Спасибо за чтение!

  • Анимированная заставка на экран блокировки windows 10
  • Антанта запуск на windows 7
  • Анимированные обои на рабочий стол для windows 10 как установить
  • Анимационная заставка на рабочий стол windows 10
  • Антивирус windows 10 сам включается