How to generate a random RGBA color and opacity in VB.NET

1 Answer

0 votes
Imports System

Module RandomRGBAProgram

    ' Generate a random integer in the range [0, 255]
    Private Function RandomChannel(rnd As Random) As Integer
        Return rnd.Next(0, 256)
    End Function

    ' Generate a random opacity in the range [0, 1]
    Private Function RandomOpacity(rnd As Random) As Double
        Return rnd.NextDouble()   ' full precision floating‑point
    End Function

    ' Create a random RGBA color string
    Private Function RandomRGBA() As String
        Dim rnd As New Random()   ' automatically seeded

        Dim r As Integer = RandomChannel(rnd)
        Dim g As Integer = RandomChannel(rnd)
        Dim b As Integer = RandomChannel(rnd)
        Dim a As Double = RandomOpacity(rnd)

        ' Format as rgba(r, g, b, a) with two decimal places
        Return $"rgba({r}, {g}, {b}, {a:F2})"
    End Function

    Sub Main()
        Dim color As String = RandomRGBA()
        Console.WriteLine(color)
    End Sub

End Module


'
' run:
'
' rgba(177, 210, 223, 0.97)
'

 



answered Aug 25 by avibootz
...