C#的pictureBox怎样使用多张图片简单切换

时间:2021-05-18 15:52:14

首先,先创建一个新的winform项目ImageTest,选择窗体,起名我ImageForm,在ImageForm拉一个picturebox控件,一个控制器trimer,一个相册imageList,在imagesList控件中Images添加你要切换的图片,并设置一下图片的大小。以下是实际代码实现

public partial class ImageForm : Form
    {
        public ImageForm()
        {
            InitializeComponent();
        }
        private int ImageIndex = 0;
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="imagelist">存放图片集合</param>
        /// <param name="picturebox">显示图片的框</param>
        private void ImageForm_Load(object sender, EventArgs e)
        {
            //初始化显示第一张图片
            this.pictureBox.Image = this.imageList1.Images[0];
            //设置定时器切换时间间隔
            this.timerImage.Interval = 1000;
            //禁用定时器
            this.timerImage.Enabled = false;
            //设置图片的大小
           // this.imageList1.ImageSize = new Size(150,150) ;
        }
        /// <summary>
        /// 播放图片事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            //启动定时器
            this.timerImage.Enabled = true;
        }
        /// <summary>
        /// 停止图片事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            this.timerImage.Enabled = false;
        }
        /// <summary>
        /// 定时器所做的事情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerImage_Tick(object sender, EventArgs e)
        {

    //当下标大于或等于相册图片个数时,返回第一张(即到了最后一张时,切换到第一张)
            if(ImageIndex >= this.imageList1.Images.Count){
                ImageIndex = 0;
            }

    //把相册imageList中的图片一一显示在picturebox中
            this.pictureBox.Image = this.imageList1.Images[ImageIndex++];
        }
    }