簡體   English   中英

如何使用C#在Visual Studio中的圖片框中訪問圖像的名稱

[英]How do you access the name of the image in a picturebox in Visual Studio using C#

我有一個程序,其中有16個使用圖片框的網格圖塊,但僅使用5張圖像,其余圖塊只是黑色圖像。

我想知道“用戶”點擊哪個圖像。

我有一個名為image_Click(object sender,EventArgs e)的方法

我在此方法中有一條if語句,指出:

if (peckedSquare.BackColor == Color.Black)
{
    System.Diagnostics.Debug.WriteLine("Pecked a black square");
    return;
}

這會發送一個字符串,讓我知道何時單擊了黑色正方形。

有沒有一種簡單的方法可以說:

//偽代碼:

if (peckedSquare.ImageName == pigeon1.png)
{
    System.Diagnostics.Debug.WriteLine("Pecked Pigeon number 1");
}

我已經用Google搜索了我的查詢,但是沒有找到合適的答案。

//編輯我剛剛重新閱讀了我的代碼。 我使用隨機數將每張圖片分配到一個圖片框正方形。 我使用此隨機數作為變量,因此我可以使用該變量來確定單擊了哪個圖像。 即。

if (randomNumber == 1)
{
    System.Diagnostics.Debug.WriteLine("Pecked Pigeon number 1");
}

或比那更好

pigeonSelected = randomNumber + 1 //as I am using an array to store the images
System.Diagnostics.Debug.WriteLine("Pecked Pigeon Number {0}", pigeonSelected);

作為一種快速且骯臟的解決方案,我將使用Tag屬性,對於黑色磁貼使用null屬性,對於其他磁貼使用文件路徑(即使您的圖像來自資源,它始終可用),如下所示:

if (peckedSquare.Tag == null)
{
    Debug.WriteLine("Pecked a black square");
}
else
{
    switch (Path.GetFileName(peckedSquare.Tag.ToString()))
    {
        case "pigeon1.png":
        break;
    }
}

當然,當您創建圖塊時,必須將文件路徑存儲在Tag

PictureBox tile = new PictureBox();
tile.Image = Image.FromFile(path); // Or another source, of course
tile.Tag = path;

作為替代,您甚至可以為此使用Name屬性,每個控件都被命名(主要用於設計器代碼集成),但是如果您在運行時創建控件,則可以將該值設置為所需的任何值(不僅是有效的標識符)。 與上面相同的用法只是不需要調用ToString()

怎么提高?

請讓我說這種解決方案不是非常面向對象的。 即使不進行大量重構,我們也可以做得更好。 請注意,您可以在Tag屬性中存儲任何內容。 一個數字,一個與文件名無關的簡單字符串,或者甚至(可能更好)一個代表該圖像的classenum (將動作委派給該對象)。 這是一個非常原始的示例:

abstract class Tile {
    public abstract void Activate();
}

sealed class EmptyTile : Tile {
    public virtual void Activate() {
        Debug.WriteLine("Pecked a black square");
    }
}

sealed class ImageTile : Tile {
    public ImageTile(string content) {
        _content = content;
    }

    public virtual void Activate() {
        Debug.WriteLine(_content);
    }

    private string _content;
}

通過這種方式,您可以在click事件處理程序中執行以下操作:

((Tile)peckedTile.Tag).Activate();

無需檢查內部內容或與null比較。 不, if沒有,也沒有switch ,只是在創建圖塊時不要忘記放置適當的對象( ImageTileBlackTile )。

使用PictureBox.Load(string)方法從文件加載圖像。 然后,文件路徑將存儲在PictureBox.ImageLocation屬性中:

調用Load方法將覆蓋ImageLocation屬性,將ImageLocation設置為方法調用中指定的URL值。

因此,您可以編寫例如:

if (peckedSquare.ImageLocation.EndsWith("pigeon1.png"))
{
    System.Diagnostics.Debug.WriteLine("Pecked Pigeon number 1");
}

您可以使用Tag屬性(例如@Adriano建議)執行以下操作:

public Form1()
{
    InitializeComponent();
    pictureBox1.Click += pictureBox_Click;
    pictureBox2.Click += pictureBox_Click;
    pictureBox3.Click += pictureBox_Click;
    // ...
    pictureBox1.Tag = "picture1.png";
    pictureBox2.Tag = "picture2.png";
    pictureBox3.Tag = "picture3.png";
}

void pictureBox_Click(object sender, EventArgs e)
{
    PictureBox pb = sender as PictureBox;

    if (pb.BackColor != Color.Black)
        Debug.WriteLine(pb.Tag.ToString());
    else
        Debug.WriteLine("Black image");

}

我認為您可以執行以下操作:

    private List<PictureBox> pictures = null;
    string[] ImageNames = new string[]
            {
                "images\\test_1.jpg",
                "images\\test_2.jpg"
            };

    private void Form1_Load(object sender, EventArgs e)
    {

        pictures = new List<PictureBox>();
        for (var idx = 0; idx < ImageNames.Length; idx++)
        {
            pictures.Add(new PictureBox());
            pictures[idx].Image = new Bitmap(ImageNames[idx]);
            pictures[idx].Click += OnClick;

            // you'll want to set the offset and everything so it shows at the right place
            Controls.Add(pictures[idx]);
        }
    }

    private void OnClick(object sender, EventArgs eventArgs)
    {
        // you'll definitely want error handling here
        var ImageName = ImageNames[pictures.IndexOf((PictureBox) sender)];
    }

您可以看到,在click方法中,您將能夠獲得圖像名稱,這正是您所希望的。

正如其他人所說的,您還可以使用“ Tag”屬性,前提是您尚未將其用於其他用途。 關於tag的好處是,您還可以通過表單設計器對其進行編輯,這使您可以比上面使用的自動布局更好地進行布局。 祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM