繁体   English   中英

VB.NET如何检查我的资源中的图像是否已加载到PictureBox中?

[英]VB.NET How can I check if an image from my resources is loaded in a PictureBox?

我试图使PictureBox在按下时更改图像,如果再次按下,它将更改为原始图像。 我怎样才能做到这一点? 这是我的代码。

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
    If (PictureBox1.Image = WindowsApplication1.My.Resources.Resources.asd) Then
        PictureBox1.Image = WindowsApplication1.My.Resources.Resources._stop()
    Else
        PictureBox1.Image = WindowsApplication1.My.Resources.Resources.asd()
    End If
End Sub

当我运行它时,它给出以下错误:

 Operator '=' is not defined for types "Image" and "Bitmap". 

好吧,这是一个很好的问题。 My.Resources属性获取器中隐藏着一个巨大的熊陷阱,每次使用它时,都会得到一个新的位图对象。 这会带来很多后果,位图是非常昂贵的对象,并且调用它们的Dispose()方法对于防止程序内存不足非常重要。 由于它是新对象,因此比较将始终失败。 图像和位图之间的区别只是一个小问题。

仅一次使用位图对象至关重要。 像这样:

Private asd As Image = My.Resources.asd
Private _stop As Image = My.Resources._stop

现在,您正在正确编写此代码,因为您正在比较对象的引用标识:

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
    If PictureBox1.Image = asd Then
        PictureBox1.Image = _stop
    Else
        PictureBox1.Image = asd
    End If
End Sub

就像一个优秀的程序员一样,您可以在不再使用图像对象时对其进行处置:

Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
    asd.Dispose()
    _stop.Dispose()
End Sub

还要修复首先分配PictureBox1.Image属性的代码,我们看不到它。

您可以使用PictureBox的.Tag属性存储信息。 为此,我将存储资源名称。

如果有要使用的资源名称数组,则可以获取下一个(使用Mod从最后一个到第一个(在VB.NET中,数组索引从零开始)环绕)。

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
    Dim imageResourceNames = {"Image1", "Image2"}

    Dim pb = DirectCast(sender, PictureBox)
    Dim tag = CStr(pb.Tag)
    pb.Image?.Dispose()

    Dim nextImage = imageResourceNames((Array.IndexOf(imageResourceNames, tag) + 1) Mod imageResourceNames.Length)

    pb.Image = DirectCast(My.Resources.ResourceManager.GetObject(nextImage), Image)
    pb.Tag = nextImage

End Sub

请根据需要更改“ Image1”和“ Image2”。

如果搜索的项不在数组中,则Array.IndexOf将返回-1,但是我们要向其添加1,因此如果未设置.Tag ,它将获得数组的第一项(索引为0)。

如果有第三张图像,则只需将其名称添加到数组中。

PictureBox1.Image?.Dispose()处理图像使用的资源- ? 仅当PictureBox1.Image为Nothing时才这样做。

首次设置PictureBox的图像时,请记住适当设置其.Tag属性,以使其表现出预期的效果。

我使用了Dim pb = DirectCast(sender, PictureBox)这样您就可以简单地将代码复制并粘贴到其他PictureBox中,并且代码中几乎没有更改-否则,您必须将对PictureBox1的引用全部更新通过它,可能容易出错。 当然,到那时,您将开始考虑对其进行重构,以便不重复代码(“不要重复自己”或DRY原理)。

暂无
暂无

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

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