2

現在、画像ボックスに画像をロードするために次のコードを使用しています。

pictureBox1.Image = Properties.Resources.Desert;

コードが次のように機能するように、「砂漠」を「変数」に置き換えます。

String Image_Name;
Imgage_Name = "Desert";
pictureBox1.Image = Properties.Resources.Image_Name;

イメージごとに個別の行を記述する代わりに、イメージ名に変数を使用してロードする必要がある多数のイマジンがあります。これは可能ですか?

4

2 に答える 2

2

リソースを反復処理できます..次のようにします。

using System.Collections;

string image_name = "Desert";

foreach (DictionaryEntry kvp in Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true)) {
    if ((string)kvp.Key == image_name) {
        var bmp = kvp.Value as Bitmap;
        if (bmp != null) {
            // bmp is your image
        }
    }
}

あなたは素敵な小さな関数でそれをラップすることができます..次のようなもの:

public Bitmap getResourceBitmapWithName(string image_name) {
    foreach (DictionaryEntry kvp in Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true)) {
        if ((string)kvp.Key == image_name) {
            var bmp = kvp.Value as Bitmap;
            if (bmp != null) {
                return bmp;
            }
        }
    }

    return null;
}

使用法:

var resourceBitmap = getResourceBitmapWithName("Desert");
if (resourceBitmap != null) {
    pictureBox1.Image = resourceBitmap;
}
于 2013-07-22T03:16:54.840 に答える
1

これをチェックしてください:オブジェクトをインスタンス化するときに、文字列をプログラムでオブジェクト名として使用します。デフォルトでは、C# ではこれを行うことができません。ただし、 を使用してstringから必要な画像にアクセスすることはできますDictionary

次のようなことを試すことができます:

Dictionary<string, Image> nameAndImg = new Dictionary<string, Image>()
{
    {"pic1",  Properties.Resources.pic1},
    {"pic2",  Properties.Resources.pic2}
    //and so on...
};

private void button1_Click(object sender, EventArgs e)
{
    string name = textBox1.Text;

    if (nameAndImg.ContainsKey(name))
        pictureBox1.Image = nameAndImg[name];

    else
        MessageBox.Show("Inavlid picture name");
}
于 2013-07-22T03:15:21.460 に答える