Results 1 to 2 of 2

Thread: Color Randomizer

  1. #1

    Thread Starter
    King of sapila
    Join Date
    Oct 2006
    Location
    Greece
    Posts
    6,597

    Color Randomizer

    Just for fun.

    This will pick random colors on an winforms app.

    Code:
    ' cons
      Dim ColorNames As New List(Of String)
    
    ''use as
     '  ColorNames = colorrandomizerBegin()
    '   Label1.ForeColor = colorrandomizer()
    
    
    Private Function colorrandomizerBegin() As List(Of String)
            Dim ColorName As System.Type = GetType(System.Drawing.Color)
            Dim ColorPropInfo As System.Reflection.PropertyInfo() = ColorName.GetProperties()
    
            For Each CPI As System.Reflection.PropertyInfo In ColorPropInfo
                If CPI.PropertyType.Name = "Color" And CPI.Name.tolower() <> "transparent" Then
                    ColorNames.Add(CPI.Name)
                End If
            Next
            Return ColorNames
        End Function
    
     Private Function colorrandomizer() As Color
            Dim randomx As New Random
    
            Dim s As Color
            s = Color.FromName(ColorNames(randomx.Next(0, ColorNames.Count)))
    
            Do While s = Me.ForeColor Or s = Me.BackColor
                s = Color.FromName(ColorNames(randomx.Next(0, ColorNames.Count)))
            Loop
            Return s
    
        End Function
    ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
    πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν·

  2. #2
    Lively Member
    Join Date
    Jun 2018
    Posts
    80

    Re: Color Randomizer

    Your code only returns named system colors. This makes it more useful for Form designs, ect..

    However, having only a few colors out of more than 16 millions might not fit everyone's needs so i'm just posting this small code in case this happens.

    Randomizes via RGB to get all possible outputs.

    Code:
        Function RandomColor() As Color
            Dim valueR As Integer = CInt(Int(256 * Rnd()))
            Dim valueG As Integer = CInt(Int(256 * Rnd()))
            Dim valueB As Integer = CInt(Int(256 * Rnd()))
            Dim RndColor As Color = Color.FromArgb(valueR, valueG, valueB)
            Return RndColor
        End Function
    Cheers,

    KBConsole
    Last edited by KBConsole; Jun 14th, 2018 at 08:44 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width