从面板图像gallary将图像加载到图片框

时间:2016-09-03 06:35:00

标签: c# .net winforms

我使用将多个图像添加到面板中,在Windows窗体应用程序中创建了一个图库。现在我想将点击的图像加载到另一个图片框中。有没有人可以帮助我?

我的代码

OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "JPG|*.jpg|JPEG|*.jpeg|PNG|*.png";
ofd.Multiselect = true;
DialogResult dr = ofd.ShowDialog();
if(dr==DialogResult.OK)
{
    int x = 20;
    int y = 20;
    int maxHeight = -1;
    string[] files = ofd.FileNames;
    foreach (string img in files)
    {
        PictureBox pic = new PictureBox();
        pic.Image = System.Drawing.Image.FromFile(img);
        pic.SizeMode = PictureBoxSizeMode.StretchImage;
        pic.Location = new System.Drawing.Point(x, y);
        x += pic.Width + 10;
        maxHeight = Math.Max(pic.Height, maxHeight);
        if(x > this.pnlGallary.Width - 100)
        {
            x = 20;
            y += maxHeight + 10;
        }
        this.pnlGallary.Controls.Add(pic);
    }
}

Sample Image is Here

1 个答案:

答案 0 :(得分:2)

请替换您的代码,如下所示:

13012016

为动态生成的OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "JPG|*.jpg|JPEG|*.jpeg|PNG|*.png"; ofd.Multiselect = true; DialogResult dr = ofd.ShowDialog(); if (dr == DialogResult.OK) { int x = 20; int y = 20; int maxHeight = -1; string[] files = ofd.FileNames; foreach (string img in files) { PictureBox pic = new PictureBox(); pic.Click += new EventHandler(pictureBox_Click); // call the custom event for dynamic generated PictureBox pic.Image = System.Drawing.Image.FromFile(img); pic.SizeMode = PictureBoxSizeMode.StretchImage; pic.Location = new System.Drawing.Point(x, y); x += pic.Width + 10; maxHeight = Math.Max(pic.Height, maxHeight); if (x > this.pnlGallary.Width - 100) { x = 20; y += maxHeight + 10; } this.pnlGallary.Controls.Add(pic); } } 添加常用点击事件处理程序,如下所示

PictureBox