簡體   English   中英

從 VB.Net (2022) 中的 Resources 獲取隨機圖像文件,然后顯示在圖片框中

[英]Getting random image file from Resources in VB.Net (2022), which then displays in a picturebox

我正在為 class 編程,其中涉及制作“快照”。 游戲。

基本上代碼是這樣運行的:

Private Sub btnOne_Click(sender As Object, e As EventArgs) Handles btnOne.Click
        picOne.Visible = True 'displays picOne'
        lblDisplay.Text = "Owl" 'changes text of lblDisplay to "Owl"
        btnOne.Enabled = False 'btnOne is disabled, making it impossible to click it.
    End Sub

    Private Sub btnTwo_Click(sender As Object, e As EventArgs) Handles btnTwo.Click
        picTwo.Visible = True 'displays picOne'

        If lblDisplay.Text = "Bee" Then 'Checks if lblDisplay is "Bee"
            lblDisplay.Text = "Snap!" 'displays 'Snap!' statement above is true
        Else
            lblDisplay.Text = "Bee" 'otherwise, just displays bee, as duplicate isnt found
        End If

        btnTwo.Enabled = False 'btnTwo is disabled, making it impossible to click it.
    End Sub

然而,這非常無聊,因為相同的兩張卡片總是“快照”,我需要一種方法以便從“資源”中選擇隨機圖像。 然后顯示在圖片框中。

我不確定 go 如何從資源中獲取隨機圖像,所以如果有人可以幫助我,我將不勝感激。

謝謝。

您知道資源中有哪些圖像,因此您可以將它們的名稱硬編碼到一個String數組中,為該數組生成一個隨機索引,獲取名稱,然后從資源管理器中獲取具有該名稱的資源。

Dim imageResourceNames = {"Image1", "Image2", "Image3"}
Dim rng As New Random
Dim index = rng.Next(imageResourceNames.Length)
Dim imageResourceName = imageResourceNames(index)
Dim img = DirectCast(My.Resources.ResourceManager.GetObject(imageResourceName), Image)

如果您不想對資源名稱進行硬編碼,則可以使用與評論鏈接中提供的答案之一類似的邏輯來獲取它們:

Private Function GetResourceImageNames() As String()
    Dim properties As PropertyInfo() = GetType(My.Resources.Resources).GetProperties(BindingFlags.NonPublic Or
                                                                                     BindingFlags.Instance Or
                                                                                     BindingFlags.Static)
    Dim imageType As Type = GetType(Image)

    Return properties.Where(Function(pi) imageType.IsAssignableFrom(pi.PropertyType)).
                      Select(Function(pi) pi.Name).
                      ToArray()
End Function

和:

Dim imageResourceNames = GetResourceImageNames()
Dim rng As New Random
Dim index = rng.Next(imageResourceNames.Length)
Dim imageResourceName = imageResourceNames(index)
Dim img = DirectCast(My.Resources.ResourceManager.GetObject(imageResourceName), Image)

先獲取名稱然后只獲取一個所需的Image比獲取所有Images並丟棄除一個圖像以外的所有圖像更有效。 當然,如果您計划使用所有或大部分Images ,那么首先將它們全部放入一個數組然后反復使用該數組來獲取隨機Images可能是有意義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM