ListView显示图片失真

用listview显示快捷方式图片列表,图片一直失真,猜测各种问题。以为是获取Icon的方法有问题,但是把获取到的Icon显示在图片控件时又没问题,那就知道是ListView显示图片的问题了,网上找原因,看到别人的解释。

大家对于ImageList的问题归纳了一下,主要都是关于:   
  1.ImageList里面的图片的颜色   
  2.ImageList里面的图片的大小   
    
    
  /********* 1)ImageList里面的图片的颜色的问题 ********/   
    
    
  引起ImageList里面图片颜色失真的原因是在Design-Time就在VS.NET中往ImageList里面添加了Images。   
    
  当用户一边在“Image Collection Editor”对话框里面添加图片,VS.NET一边就已经把这些图片装载到resource文件里面了。这样,以后程序运行时就只需要访问resource文件就可以载入所有图片而不需要依赖原始的图片文件。  
    
  但是问题在于从结果看,当VS.NET在Design-Time往resource文件里面添加图片时并没有使用用户指定的ColorDepth(例如Depth32Bit),而用了ImageList.ColorDepth的默认值(Depth8Bit)。这样,等程序运行时,即使ImageList.ColorDepth指定了Depth32Bit也无济于事,因为原始的素材本身只有8bit的颜色。这基本上就是waki的问题的原因。  
    
  因此,解决方案是:不在Design-Time用VS.NET往ImageList里面添加图片,而是在程序运行时先指定32Bit的ColorDepth,然后再添加图片,如以下例子代码:  
    
  this.imageList1.ColorDepth=ColorDepth.Depth32Bit;   
  this.imageList1.Images.Add(Image.FromFile(@"C:Inetpubwwwrootwinxp.gif"));   
  this.imageList1.Images.Add(Image.FromFile(@"C:Inetpubwwwrootimagesinit_dotnet.gif"));  
  this.imageList1.Images.Add(Image.FromFile(@"C:Inetpubwwwrootimagesmslogo.gif"));  
  this.imageList1.Images.Add(Image.FromFile(@"C:Inetpubwwwrootimagesmslogo2.gif"));  
    
  这里需要注意的是,必须先指定ColorDepth,然后再添加图片。因为对ColorDepth赋值会清空所有图片。BTW,ImageList.ColorDepth的默认值是Depth8Bit,而非文档上所述Depth4Bit。这一点很容易可以通过写一段例子代码来验证,也可以通过很多Decompiler来查看ImageList的构造函数的实现来验证。  
    
    
  /********** 2)ImageList里面的图片的大小 ************/   
    
    
  的确,通过ImageList.Images[i]获得图片的大小都是统一的,都等于ImageList.ImageSize。这个问题的原因在于ImageList在返回Images[i]的过程中并没有返回原始的图片,而是按照ImageList.ImageSize创建了一个新的Bitmap,并把原始图片的内容重新绘制上去以后再返回给用户。关于这一点,可以用一些Decompiler工具如ILDASM.exe或者Anakrino通过察看私有函数ImageList.GetBitmap(int index)来验证。我想现在paulluo0739应该能够理解为什么ImageList里面的图片都是一样大的了。   
    
  ImageSize同ColorDepth类似,也不宜在运行时改动,一旦重新赋值,就会清空所有的图片。因此,如果程序运行时需要某一图片的不同大小的版本,可以考虑使用多个不同ImageSize的ImageList。  
    
    
  希望以上这些能够对大家有帮助,感谢大家关心和使用微软的技术和产品。   
    
    ImageList il = new ImageList();
    il.ImageSize = new Size(32, 32);
    il.ColorDepth = ColorDepth.Depth32Bit; 
    listView.SmallImageList = new ImageList();
    listView.LargeImageList = il;
    listView.View = View.Tile;
    

原文地址:https://www.cnblogs.com/MasonRayn/p/3453644.html