【问题标题】:How to check if a picture box contains a certain image using an IF statement如何使用 IF 语句检查图片框是否包含某个图像
【发布时间】:2019-12-23 00:42:34
【问题描述】:

我正在尝试检查 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】:

虽然 PictureBox Image 可能与资源中的相同,但它们与参考不同。 (想象你有两张同一张照片的副本,虽然它们的图像相同,但它们是两张不同的照片)。

有几种方法可以做到,其中一种(简单的一种)是在设置图片时将图片框标签设置为相关值并比较该值而不是比较图片:

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 和数组中的图像项)是相同的比较可以工作对于图像,但我认为第一个解决方案更容易。

【讨论】:

    猜你喜欢
    • 2014-02-08
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    相关资源
    最近更新 更多