简体   繁体   English

制作一组图片框,每个图片框具有不同的图像

[英]Making an array of pictureboxes, each with different images

I have 100 files in Resources named "1.png", "2.png". 我在参考资料中有100个文件,分别为“ 1.png”,“ 2.png”。 I have a PictureBox[] array generated with code, and I want to set array[i].Image = string.Format("Properties.Resources.{0}.png", i); 我有一个用代码生成的PictureBox[]数组,我想设置array[i].Image = string.Format("Properties.Resources.{0}.png", i); But this does not work. 但这是行不通的。

What is the best way to do this? 做这个的最好方式是什么?

If your images have names that conform to some pattern inside the resource file (like "Image1", "Image2", etc.), you may load them by their names: 如果图像的名称符合资源文件中的某些模式(例如“ Image1”,“ Image2”等),则可以按其名称加载它们:

ResourceManager rm = Resources.ResourceManager;
array[i].Image = (Bitmap)rm.GetObject(string.Format("Image{0}", i));

you can refer to this post. 您可以参考这篇文章。

or you can simply use : 或者您可以简单地使用:

array[i].Image = Properties.Resources.img1 

You need to use Reflection, Something like following would do the task: 您需要使用Reflection,执行以下操作:

var properties = typeof(Properties.Resources).GetProperties
    (BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

PictureBox[] array = new PictureBox[100];
int counter = 0;
foreach (PropertyInfo property in properties)
{
    var image = property.GetValue(null, null) as System.Drawing.Bitmap;
    if (image != null && counter < array.Length)
    {
        array[counter] = new PictureBox();
        array[counter++].Image = image;
    }
}

Remember to include using System.Reflection; 记住要包括using System.Reflection; at the top. 在顶部。

namespace your_name_project
{
    public partial class Form_Begin : Form
    {
        PictureBox[] pictureBoxs = new PictureBox[6];
        public Form_Begin()
        {
            InitializeComponent();
            pictureBoxs[0] = pictureBox1; pictureBoxs[1] = pictureBox2; pictureBoxs[2] = pictureBox3;
            pictureBoxs[3] = pictureBox4; pictureBoxs[4] = pictureBox5;   pictureBoxs[5] = pictureBox6;     
        }
//continue 
        List<PictureBox> pictureBoxes = new List<PictureBox>();

            private void buttonX1_Click(object sender, EventArgs e)
            {
                for (int i = 0; i <3; i++)
                {
                    pictureBoxs[i].Image =your_name_project.Properties.Resources.image_1;// load image1 and Image_2from resource in property of picturebox  
                }
                for (int i = 3; i < 6; i++)
                {
                    pictureBoxs[i].Image = your_name_project.Properties.Resources.Image_2;
                }
            } 
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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