![](/img/trans.png)
[英]How to make automated image slideshow using imagelist & timer in C#?
[英]C# How to check if a PictureBox contains an image in a specified imagelist?
我需要知道PictureBox
是否在指定的imageList
包含一個Image
。 因為如果ImageList長,如果imageList
中的每個圖像都在PictureBox中, if-statement
在if-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
是否是個好主意是另一個問題。
它實際上是與ListViews
, TreeViews
以及其他可以顯示小圖標圖像的控件一起使用的。
例如,限制為256x256像素; 還:其所有圖像必須具有相同的尺寸!
但是,如果可以,請繼續使用。
否則,如Hans所建議的那樣, List<Image>
是一種自然而靈活的選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.