簡體   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