ImageList in C#

In this article, I will discuss how to create an ImageList control and how to use its properties and methods to use in a Windows Forms application.



An ImageList is a supporting control that is typically used by other controls, such as a ListView but is exposed as a component to developers. We can use this component in our applications when we are building our own controls such as a photo gallery or an image rotator control. 
In this article, I will discuss how to create an ImageList control and how to use its properties and methods to use in a Windows Forms application.

Creating an ImageList

ImageList class represents the ImageList First step to create a dynamic ImageList is to create an instance of ImageList class. The following code snippet creates an ImageList control object.

ImageList photoList = new ImageList();

 

In the next step, you may set properties of an ImageList control. The following code snippet sets a few properties of an ImageList.

photoList.TransparentColor = Color.Blue;

photoList.ColorDepth = ColorDepth.Depth32Bit;

photoList.ImageSize = new Size(200, 200);

 

Unlike other Windows Forms control, you can't add ImageList control to a Form. You need to draw an ImageList control using the Draw method. The Draw method takes a Graphics object that is the handle of the container control that will be used as a drawing canvas.

 

photoList.Draw(g, new Point(20, 20), count);


Setting ImageList Properties

ColorDepth property represents the color depth of the image list.

ImageSize property represents the size of the images in the image list.

Images property represents all images in an ImageList as an ImageCollection object.

The following code snippet sets these properties and adds three images to the ImageList control and later loops through the images and displays them on a Form.

Graphics g = Graphics.FromHwnd(this.Handle);

 

ImageList photoList = new ImageList();

photoList.TransparentColor = Color.Blue;

photoList.ColorDepth = ColorDepth.Depth32Bit;

photoList.ImageSize = new Size(200, 200);

 

photoList.Images.Add(Image.FromFile(@"C:\Images\Garden.jpg"));

photoList.Images.Add(Image.FromFile(@"C:\Images\Tree.jpg"));

photoList.Images.Add(Image.FromFile(@"C:\Images\Waterfall.jpg"));

 

for (int count = 0; count < photoList.Images.Count; count++)

{

    photoList.Draw(g, new Point(20, 20), count);

 

    // Paint the form and wait to load the image

    Application.DoEvents();

    System.Threading.Thread.Sleep(1000);

}

 

Summary
In this article, we discussed discuss how to create and use an ImageList control in a Windows Forms application.