winForm ImageList图像控件使用

ImageList控件可以存储一系列的图片文件,可以通过索引调用显示图片和删除一张图片或全部清除。

新建窗口文件,布局如下:

添加3个【Button】控件,一个【pictureBox】控件,一个【ImageList】控件

右键【ImageList1】控件,点击【选择图像】,打开【图像集合编辑器】

单击【添加】,逐个添加需要的图片。点击【确定】

改变【ImageList】控件的【ImageSize】属性为【250, 200】

双击【显示图片1】按钮

设置代码如下:

private void button1_Click(object sender, EventArgs e)

{

if (imageList1.Images.Count > 0) //如果图像列表中存在第一张图片

{

pictureBox1.Image = imageList1.Images[0];

MessageBox.Show("显示第1张图片");

}

else

{

MessageBox.Show("未找到第1张图片");

}

}

双击【显示图片2】按钮

private void button1_Click(object sender, EventArgs e)

{

if (imageList1.Images.Count > 0) //如果图像列表中存在第2张图片

{

pictureBox1.Image = imageList1.Images[0];

MessageBox.Show("显示第2张图片");

}

else

{

MessageBox.Show("未找到第2张图片");

}

}

双击【清空图片】按钮代码,将列表中的图片全部清空

private void button3_Click(object sender, EventArgs e)

{

imageList1.Images.Clear(); //清空图片列表

MessageBox.Show("清空图片列表");

}

**.cs中全部代码

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace loginView

{

public partial class Form5 : Form

{

public Form5()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

if (imageList1.Images.Count > 0) //如果图像列表中存在第一张图片

{

pictureBox1.Image = imageList1.Images[0];

MessageBox.Show("显示第1张图片");

}

else

{

MessageBox.Show("未找到第1张图片");

}

}

private void button2_Click(object sender, EventArgs e)

{

if (imageList1.Images.Count > 1) //如果图像列表中存在第一张图片

{

pictureBox1.Image = imageList1.Images[1];

MessageBox.Show("显示第2张图片");

}

else

{

MessageBox.Show("未找到第2张图片");

}

}

private void button3_Click(object sender, EventArgs e)

{

imageList1.Images.Clear(); //清空图片列表

MessageBox.Show("清空图片列表");

}

}

}

测试代码

遗留问题:

1)pictureBox1无法清空图片

2) ImageList大小无法调节与pictureBox1大小一致,导致显示的图片过小

热门