简体   繁体   English

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

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

I need to know whether the PictureBox contains an Image in a specified imageList . 我需要知道PictureBox是否在指定的imageList包含一个Image Because if ImageList is long, it will take a lot to say in an if-statement if each image in imageList is in the PictureBox. 因为如果ImageList长,如果imageList中的每个图像都在PictureBox中, if-statementif-statement要花很多时间。 and when I type 当我键入

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

It doesn't work :/ 它不起作用:/

Try the following: 请尝试以下操作:

//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 is a special thing and it may or may not be the right object to use.. ImageList是一件特殊的事情,它可能是正确对象,也可能不是正确对象。

One good thing about it is that it stores the images not as type Image ; 一件好事是它存储的图像不是Image类型的; this is good because it doesn't need a GDI handle for each image it stores, even if you add a large number of images. 这样很好,因为即使您添加了大量图像,它也不需要为其存储的每个图像使用GDI句柄。

One problem with this is that you simply can't compare its images to an image you have assigned to a PictureBox.Image . 这样做的一个问题是,您根本无法将其图像与分配给PictureBox.Image的图像进行比较。

So even after correcting your syntax this will not work: 因此,即使在更正了语法之后,此操作也将无法进行:

// 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
    }
}

Instead you should store the Key to the image in the ImageList : 相反,您应该将图像的Key存储在ImageList

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

Now you can easily look for the key: 现在,您可以轻松地寻找关键:

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

Of course the question if using an ImageList is a good idea in the first place is quite another matter.. 当然,首先使用ImageList是否是个好主意是另一个问题。

It is really meant to be used with ListViews , TreeViews and other Controls that can display small iconic images. 它实际上是与ListViewsTreeViews以及其他可以显示小图标图像的控件一起使用的。

It is limited to 256x256 pixels for instance; 例如,限制为256x256像素; also: all its images must have the same size! 还:其所有图像必须具有相同的尺寸!

But if that is OK, stay with it. 但是,如果可以,请继续使用。

Otherwise a List<Image> , as Hans suggested would be a natural and flexible alternative.. 否则,如Hans所建议的那样, List<Image>是一种自然而灵活的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM