存储图像控件ImageList用于存储图像资源,然后在控件上显示出来,这样就简化了对图像的管理。ImageList控件实际上相当于一个图片集,也就是将多个图片存储到图片集中,当想要对某一图片进行操作时,只需要根据其图片的编号,就可以找出该图片,并对其进行操作。
ImageList时一个无法再窗体中直接显示的控件。在将其拖放到窗体上时,它并不会显示于窗体上,而是在窗体的内部以代码的形式存在,并包含所有需要存储的组件。这个功能可以防止非用户界面组成的控件遮挡窗体设计器。ImageList控件的位置是固定的,无法由Top等属性更改其坐标。
1、在ImageList控件中添加图像
使用ImageList控件的Images属性的Add()方法,可以以编程的方式向ImageList控件中添加图像。
Add方法的功能是将指定图像添加到ImageList中。
例:创建一个Windows应用程序,首先使用打开对话框获取图像的路径,然后通过ImageList控件的Images属性的Add方法向控件添加图像。代码如下:
private void button1_Click(object sender, EventArgs e){
if (openFileDialog1.ShowDialog() == DialogResult.OK) { //如果在打开对话框中单击了“打开”按钮
string path = openFileDialog1.FileName; //获取所选图像路径
Image image = Image.FromFile( path, true ); //创建一个Image对象
imageList1.Images.Add( image ); //使用Image属性的Add方法向控件中添加图像
pictureBox1.Image = imageList1.Images[i]; //设置要在PictureBox控件上显示的图片
i++;
}
}
说明:若要使图像列表与一个控件关联,请将该控件的ImageList属性设置为ImageList主键的名称。
2、在ImageList控件中删除图像
在ImageList控件中可以使用RemoveAt方法移除单个图像或使用Clear方法清除图像列表中的所有图像。
注:RemoveAt方法中的索引必须有效,否则运行时将发生异常。
例:创建一个Windows应用程序,设置在控件上显示的图像,使用Images属性的RemoveAt方法将图像移除。
private void button2_Click(object sender, EventArgs e){
if (imageList1.Images.Count > 0) { //还有图像
if (imageList1.Images.Count > 1) { //如果有多于一个图像
if (i >= imageList1.Images.Count) { //如果索引大于图像
i = 0;
}
imageList1.Images.RemoveAt(i); //使用RemoveAt方法删除图像
pictureBox1.Image = imageList1.Images[i]; //设置在PictureBox控件上显示图片
MessageBox.Show("已删除图像!");
}
else{
imageList1.Images.RemoveAt(i); //使用RemoveAt方法删除图像
pictureBox1.Image = null; //PictureBox控件不显示图片
MessageBox.Show("已删除全部图像!");
}
}
else {
MessageBox.Show( "已删除图像,控件中已无可删除图像" );
}
}
3、ImageList控件的部分属性及其说明
属性 | 说明 |
Images | 包含关联控件将要使用的图片。每个单独的图像可以通过其索引值或其键值来访问 |
ImageSize | 获取或设置图像列表中的图像大小 |
ColorDepth | 获取图像列表的颜色深度 |
获取或设置被视为透明的颜色 |
注:更多属性和方法说明见:
http://msdn.microsoft.com/zh-cn/library/System.Windows.Forms.ImageList(v=vs.110).aspx