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

时间:2013-05-06 11:10:44

标签: c# image resources

我在资源中有100个名为“1.png”,“2. png”的文件。我有一个用代码生成的PictureBox[]数组,我想设置array[i].Image = string.Format("Properties.Resources.{0}.png", i);但这不起作用。

这样做的最佳方式是什么?

4 个答案:

答案 0 :(得分:4)

如果您的图像的名称符合资源文件中的某些模式(如“Image1”,“Image2”等),您可以按名称加载它们:

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

答案 1 :(得分:2)

您可以参考this帖子。

或者你可以简单地使用:

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

答案 2 :(得分:2)

你需要使用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;
    }
}

请务必在顶部加入using System.Reflection;

答案 3 :(得分:1)

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;
                }
            } 
        }
}