将 PNG 从资源加载到图片框中(使用随机输入生成器)

本文关键字:随机 输入 资源 PNG 加载 | 更新日期: 2023-09-27 18:34:50

我在资源中有大约 600 张格式为这样的图像:

戳 (1(.png

戳 (2(.png

戳 (3(.png

等等。

这是我正在处理的代码示例:

pictureBox1.Image = (Image)Properties.Resources.poke__1_;

该行代码用于加载第一个图像,如poke(1(.png

但是我希望能够加载这样的随机图像:

int num = rand.Next(0, 600);
pictureBox1.Image = (Image)Properties.Resources.poke__**num**_;

但是没有办法将变量直接插入资源名称;我能做些什么来解决这个问题?

将 PNG 从资源加载到图片框中(使用随机输入生成器)

你可以做:

string name;
// Generate the random name.
pictureBox1.Image = (System.Drawing.Image)Properties.Resources.ResourceManager.GetObject(name, Properties.Resources.Culture);

此外,如果您确定这是设置映像的唯一位置,为了提高内存性能,您可能需要释放旧映像:

using (pictureBox1.Image)
{
    pictureBox1.Image = (System.Drawing.Image)Properties.Resources.ResourceManager.GetObject(name, Properties.Resources.Culture);
}

此处必须使用原始文件名 poke ({0}).png ,而不是静态属性名称,其中 c# 属性名称中无效的字符将替换为下划线。

当然,您将丢失从静态资源管理器属性获取映像时获得的编译时类型检查。

更新

如果不想对精确数量的图像属性进行硬编码,则可以使用反射并查询名称与模式匹配Properties.Resources中的所有图像值静态属性,如下所示:

public static class ResourceHelper
{
    public static PropertyInfo [] GetStaticPropertiesOfType<TValue>(Type type)
    {
        return type
          .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
          .Where(p => typeof(TValue).IsAssignableFrom(p.PropertyType) && p.GetIndexParameters().Length == 0 && p.GetGetMethod(true) != null)
          .ToArray();
    }
}

然后,在你的课堂上:

        var regex = new Regex(@"^poke__'d+_$");
        var propertyDictionary = ResourceHelper.GetStaticPropertiesOfType<Image>(typeof(Properties.Resources)).Where(p => regex.IsMatch(p.Name)).ToDictionary(p => p.Name);
        foreach (var property in propertyDictionary.Values)
        {
            pictureBox1.Image = (Image)property.GetValue(null, null);
        }

在这里,您应该使用已替换无效属性字符的损坏名称poke__{0}_