Populating a FlowLayoutPanel with a large number of controls and painting thumbnails on demand

随声附和 提交于 2019-12-04 22:24:45

问题


I'm trying to make an ImageListBox kind of control that will display a large numbers of thumbnails, like the one that Picasa uses.

This is my design:

I have a FlowLayoutPanel that is populated with a lot of UserControl objects, for example 4,000. Each UserControl is assigned a delegate for the Paint event. When the Paint event is called, it checks a memory cache for the thumbnail and if the image is not in cache, it retrieves it from the disk.

I have two problems that I'm trying to solve:

  1. It seems that WinForms will trigger a Paint event even if the UserControl is not in view. Only 10 or so controls are in fact in view, the rest are not (the FlowLayoutPanel.AutoScroll is set to true). As a result, it tries to retrieve thumbnails for all the images and that takes a long time.

  2. Adding the UserControl objects to the FlowLayoutPanel takes a somewhat long time, about 2-3 seconds. I can live with it but I'm wondering if there is a better way to do it than:

    UserControl[] boxes = new UserControl[N];
    // populate array
    panel.SuspendLayout();
    panel.Controls.AddRange(boxes);
    panel.ResumeLayout();
    

回答1:


To improve the speed of populating the FlowLayoutPanel with your user controls, disable layout updating while you add the controls.

Immediately before your loop, call SuspendLayout() and then at the end call ResumeLayout(). Make sure to use a try-finally to guarantee the ResumeLayout() runs even if an exception occurs.




回答2:


I wouldn't add that many user controls. Rather, I'd have a series of data structures that stores information about what thumbnail to use, positioning, etc, etc, and then handle the rendering of each thumbnail required.

Of course, you would only render what you need, by checking the paint event args in your control and rendering the thumbnails that are in view and that require rendering.




回答3:


Aha! I found something.

When the UserControl is not in view and it receives a Paint event, then e.ClipRectangle.IsEmpty is true!



来源:https://stackoverflow.com/questions/470863/populating-a-flowlayoutpanel-with-a-large-number-of-controls-and-painting-thumbn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!