簡體   English   中英

C#如何檢查PictureBox是否在指定的圖像列表中包含圖像?

[英]C# How to check if a PictureBox contains an image in a specified imagelist?

我需要知道PictureBox是否在指定的imageList包含一個Image 因為如果ImageList長,如果imageList中的每個圖像都在PictureBox中, if-statementif-statement要花很多時間。 當我鍵入

foreach (var image in imageList1)
        {
            if (pictureBox1.Image = image)
            {
                //Code
            }
        }

它不起作用:/

請嘗試以下操作:

//using System.Linq;

bool isinside = /*yourImageList*/.Images.Any(x => x == /*yourPictureBox*/.Image);

if (isinside)
{
    //is in yourImageList
    MessageBox.Show("image is from imagelist!");
    //or do what you want here!
}

ImageList是一件特殊的事情,它可能是正確對象,也可能不是正確對象。

一件好事是它存儲的圖像不是Image類型的; 這樣很好,因為即使您添加了大量圖像,它也不需要為其存儲的每個圖像使用GDI句柄。

這樣做的一個問題是,您根本無法將其圖像與分配給PictureBox.Image的圖像進行比較。

因此,即使在更正了語法之后,此操作也將無法進行:

// assign an image
pictureBox1.Image = imageList1.Images[2];
// now look for it:
foreach (var  img in imageList1.Images)
{
    if (pictureBox1.Image  == img )
    {
        Console.WriteLine("Found the Image!");  // won't happen
    }
}

相反,您應該將圖像的Key存儲在ImageList

pictureBox1.Image = imageList1.Images[2];
pictureBox1.Tag = imageList1.Images.Keys[2];

現在,您可以輕松地尋找關鍵:

foreach (var  imgKey in imageList1.Images.Keys)
{
    if (pictureBox1.Tag.ToString() == imgKey )
    {
        Console.WriteLine("Found the Image-Key!");  // will happen quite quickly!
    }
}

當然,首先使用ImageList是否是個好主意是另一個問題。

它實際上是與ListViewsTreeViews以及其他可以顯示小圖標圖像的控件一起使用的。

例如,限制為256x256像素; 還:其所有圖像必須具有相同的尺寸!

但是,如果可以,請繼續使用。

否則,如Hans所建議的那樣, List<Image>是一種自然而靈活的選擇。

暫無
暫無

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

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