C#构建动画控件

Head first C#学习笔记:以构建一个动画控件为例,讲解如何构建自己的控件。

  1. 新建一个工程。并在resources下添加四张图片。
    C#构建动画控件_第1张图片
    可以随便找四张图片,或者自己画都可以。只是熟悉构建控件的过程。这里要体现蜜蜂扇动翅膀的动画过程,因此四张连续的蜜蜂翅膀变化图。
    想想:要实现一个蜜蜂动态变化的过程,首先是显示一张非动画图片,然后用一个timer控制过一段时间换成下一张图片。。。因此,这个控件很像PictureBox,只不过添加了时间控制。因此要继承一个PictureBox控件。

  2. 新建一个BeeControl类,实现动画效果。

class BeeControl:PictureBox 
    {
        private Timer animationTimer = new Timer();//创建timer新实例
        public BeeControl()
        {
            //初始化定时器
            animationTimer.Tick += new EventHandler(animationTimer_Tick);//生成tick事件
            animationTimer.Interval = 100;
            animationTimer.Start();
            BackColor = System.Drawing.Color.Transparent;
            BackgroundImageLayout = ImageLayout.Stretch;
        }

        private int cell = 0;
        void animationTimer_Tick(object sender, EventArgs e)//定时到了之后,该干嘛。
        {
            cell++;
            switch (cell)
            {
                //让四张图片轮流显示
                case 1: BackgroundImage = Properties.Resources.Bee_animation_1; break;
                case 2: BackgroundImage = Properties.Resources.Bee_animation_2; break;
                case 3: BackgroundImage = Properties.Resources.Bee_animation_3; break;
                case 4: BackgroundImage = Properties.Resources.Bee_animation_4; break;
                case 5: BackgroundImage = Properties.Resources.Bee_animation_3; break;
                default: BackgroundImage = Properties.Resources.Bee_animation_2;
                    cell = 0; break;
            }
        }

3.重新构建程序。这时就能看到工具栏多了你写的控件!拖到界面,就会看到一个扇动翅膀的小蜜蜂。
C#构建动画控件_第2张图片


如何用按钮来控制添加、删除该控件呢。


从窗体删除BeeControl,然后增加一个按钮。
向窗体增加控件很简单,只需把它增加到controls集合。从窗体中删除控件也很简单,从controls集合删除就可以了。代码如下:不过控件实现了idisposable,所以要确保删除控件后一定要将其撤销。

BeeControl control = null;
        private void button1_Click(object sender, EventArgs e)
        {
            if (control == null)
            {
                control = new BeeControl() { Location = new Point(100, 100) };//实例化一个对象
                Controls.Add(control);//向controls集合增加一个控件时,它会立即出现在窗体上
            }
            else
            {
                using (control)//利用using语句来确保从controls集合删除控件后会将其撤销
                {
                    Controls.Remove(control);
                }
                control = null;
            }
        }

C#构建动画控件_第3张图片
C#构建动画控件_第4张图片
在IDE新增的dispose()方法的最后增加代码,当disposing参数为true时调用animationTimer.Dispose():

protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (disposing)
            {
                animationTimer.Dispose();
            }
        }

在if(disposing)那一行设置一个断点,运行程序。每次从窗体的controls集合删除一个BeeControl对象时,就会调用它的dispose()方法。
如果一个控件是自己从头编写的,注意要负责撤销它创建的所有其他控件!!

构建你自己的工具控件还有一个更容易的方法,就是用userControl来构建控件。下一篇中继续。。。

代码下载:
http://download.csdn.net/detail/u013480539/9668432

你可能感兴趣的:(C#编程)