简体   繁体   中英

Load image into picturebox only when needed/visible

I'm programming a little application that shows thumbnails of images. All the displayed images are in the same directory, each Image is inside it's own groupbox with a few labels and a checkbox. All the group boxes get added to a flowlayoutpanel. The problem is, that the amount of images may get pretty large and I'm concerned that memory usage / performance might get a little out of hand if I load all images even if they're not yet visible.

Is there a way to load only images that are currently visible to the user? My first thought is storing the location of my boxes and determine which images to load depending on the scroll position, or is there an easier way to determine if a picturebox/groupbox is currently visible?

Ideally what you should be doing is creating buffer logic rather than hiding 1 image and showing the other. It's a much better idea to have a couple buffers loading the images before you show them and have a fixed number of actual fields showing images rather than a new set per image.

But if your solution requires that, try to create a custom user control.

Try something like this:

public class customUserControl : UserControl
{
    //Store image as a Uri rather than an Image
    private Uri StoredImagePath;
    public class PictureBoxAdv : PictureBox
    {
        public PictureBoxAdv()
        {
            this.VisibleChanged +=new EventHandler(VisibleChanged);
        }
    }
    public Uri Image
    {
        get { return StoredImagePath; }
        set
        {
            StoredImagePath = value;
            if (this.Visible && StoredImagePath != null)
            {
                this.Image = Image.FromFile(StoredImagePath.AbsolutePath);
            }
        }
    }
    public void VisibleChanged(object sender, EventArgs e)
    {
        //When becomes visible, restore image, invisible, nullify.
        if (this.Visible && StoredImagePath != null)
        {
            this.Image = Image.FromFile(StoredImagePath.AbsolutePath);
        }
        else
        {
            this.Image = null;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM