【问题标题】:Loading image to picture box from panel image gallary将图像从面板图像库加载到图片框
【发布时间】:2017-07-28 16:40:59
【问题描述】:

我在 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

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

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

    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 添加常见的点击事件处理程序,如下所示

    void pictureBox_Click(object sender, EventArgs e)
    {
        pictureBox1.Image = ((PictureBox)sender).Image;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多