【问题标题】:How to Compare Variable to PictureBox Image如何将变量与 PictureBox 图像进行比较
【发布时间】:2015-10-28 11:37:12
【问题描述】:
    If PictureBox1.Image = "a.png" Then
        PictureBox1.Image = My.Resources.b
    Else
        PictureBox1.Image = My.Resources.a
    End If

这行不通。我如何使这件事起作用?它应该检查图片框是否显示图片 a ,如果是则使其显示图片 b。

Public Class Form1
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick 
        If PictureBox1.Image Is My.Resources.b Then
            PictureBox1.Image = My.Resources.a
            PictureBox1.Refresh()
        Else
            PictureBox1.Image = My.Resources.b
            PictureBox1.Refresh()
        End If
    End Sub
End Class

这就是完整的代码

【问题讨论】:

  • 首先:项目属性:option strict on,option explicit on
  • 是的,我以前试过,但还是不行

标签: .net vb.net image visual-studio picturebox


【解决方案1】:

Image 是 System.Drawing.Image 类型的属性,而 "a.png" 是字符串,因此您无法比较这些内容是否相等。

另外Image 是一个引用类型,所以您必须使用Is 将其与另一个引用类型进行比较。

以下方法可能有效:

If PictureBox1.Image Is My.Resources.a Then
    PictureBox1.Image = My.Resources.b
Else
    PictureBox1.Image = My.Resources.a
End If

注意:比较图像可能会很棘手,因为当您设置 Image 属性时,它实际上可能会创建原始图像的副本,因此以后比较不起作用。见How to compare Image objects with C# .NET?

因此,考虑到这一点,使用变量来比较状态会是一个更好的主意,因为这消耗的资源更少,并且比必须比较图像要简单得多。

以下内容应该适合您:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Static showImageA As Boolean
    showImageA = Not showImageA

    If showImageA Then
        PictureBox1.Image = My.Resources.a
    Else
        PictureBox1.Image = My.Resources.b
    End If
End Sub

注意:确保您有 Option Strict 和 Option Explicit On,因为您发布的代码在您执行此操作时不会编译,因此会向您指出错误。

【讨论】:

  • 谢谢它解决了错误,但它仍然没有改变图片。你能再帮我一次吗?
  • 听起来你还有另一个问题。如果您在循环中执行此操作,请在将图像设置为快速修复后尝试PictureBox1.Refresh。
  • Public Class Form1 Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick If PictureBox1.Image Is My.Resources.b Then PictureBox1.Image = My.Resources.a PictureBox1.Refresh() Else PictureBox1.Image = My.Resources.b PictureBox1.Refresh() End If End Sub End Class
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
相关资源
最近更新 更多