如何使用IF语句检查图片框是否包含特定图像

问题描述 投票:1回答:1

我正在尝试检查PictureBox是否包含某个图像,但是我尝试这样做的方式似乎可以在我的脑海中工作,但是,不,我不确定是否还有其他方法可以检查是否窗体上的图片框包含一定的图像。

private void user_btn_Click(object sender, EventArgs e)
{         
    //If statement to check if the forms picture box contains a certain image 
    if (pictureBox1.Image == Resources.user_male_white_red_brown)
    {
         this.Hide();
         UserProfile User = new UserProfile();
         User.ShowDialog();
         User.pictureBox1.Image = Resources.user_male_white_red_brown;
         this.Close();
    }
    else if (pictureBox1.Image == Resources.user_female_olive_orange)
    {
          this.Hide();
          UserProfile User = new UserProfile();
          User.ShowDialog();
          User.pictureBox1.Image = Resources.user_female_olive_orange;
          this.Close();
     }
}
c# winforms picturebox
1个回答
0
投票

尽管PictureBox Image可能与资源中的相同,但它们与参考不同。 (想象一下,尽管您的图像是相同的,但它们是2张独立的照片,但是您有2张相同的照片)。

[有几种方法,其中一种(一种简单的方法是,每当设置图像框的图像并比较该值而不是比较图像时,都将picturebox标记设置为一个相关的值:

User.pictureBox1.Image = Resources.user_male_white_red_brown;
User.pictureBox1.Tag = "user_male_white_red_brown";

然后:

if((string)User.pictureBox1.Tag == "user_male_white_red_brown")
{
     // your logic
}

这样,每次设置图片框图像时都需要设置PictureBox标签。

另一种方法是将资源中的所有图像加载到数组中,并从该数组设置PictureBox图像,这种方式作为两个图像(picturebox.Image和数组中的图像项)的引用,对于图片,但我认为第一种解决方案更容易。

© www.soinside.com 2019 - 2024. All rights reserved.