Search code examples
.netvb.netlistviewimagelist

Changing ImageSize property of ImageList displays blank images


In my VB.Net solution in Visual Studio, I have a ListView and an ImageList associated with that ListView. It is set as the LargeImageList and SmallImageList.

Here is what it looks like without programmatically changing the ImageSize property of the ImageList:

However, if I resize the ImageList via:

ImageList1.ImageSize = New Size(64, 64)

Or any other size, I get this:

I tried calling ListView1.Refresh() afterwards, still nothing.

I even tried:

ListView1.LargeImageList.ImageSize = New Point(64, 64)

How do I dynamically set the size of the icons when the project is running? I need to be able to resize them to several sizes (i.e. 32x32, 64x64, 96x96, etc.)

The images in the ImageList are all 128x128 so that they could be scaled down easier.


Solution

  • Changing the ImageSize results in the handle being recreated which would likely break the link or assignment . That is explained on MSDN. It also warns of the images being deleted when you change the ColorDepth; but this also seems to happen when you change the size at least in some cases:

    imgLst.ImageSize = New Size(64, 64)
    Dim num = ImgLst.Images.Count          ' == 0
    

    Repeatedly changing the size for one set is probably not a good idea anyway: resizing to 128 from 32 will probably give a horrible result. What does work is to have one ImageList as the master with 128x128 images in it. When you want to change the size, copy them to the "working" ImageList in the new size:

    Private Sub LoadImagesWithSize(sz As Size)
    
        imgLst.ImageSize = sz
        imgLst.Images.Clear
        For n As Int32 = 0 To ImageList128.Images.Count - 1
            imgLst.Images.Add(ImageList128.Images(n))
        Next
        myLV.LargeImageList = imgLst
    
    End Sub
    

    Call it as:

    LoadImagesWithSize(New Size(64, 64))
    

    Rather than an ImageList for each possible size, there is one "master" along with the "active" size-version. It seems to work fine.