Click here to Skip to main content
15,897,187 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello everyone, I need a way to choose a random color from
C#
System.Drawing.Color 
, please, anyone help me...
Posted
Updated 23-Jan-18 23:02pm
Comments
BillWoodruff 6-Oct-14 14:18pm    
Seems like there are various interpretations of "random color from System.Drawing.Color:" do you mean you want any color possible; or, do you mean that you want a random color chosen from a sub-set of the Colors, like those found in the KnownColor Enumeration ?

Assuming you want a random selection from the Known Colors in System.Drawing:
C#
private List<knowncolor> colorList;
private Random rand;
private int maxColorIndex;

private KnownColor getRandomColor()
{
    return colorList[rand.Next(0, maxColorIndex)];
}

private TestRandomKnownColor()
{
    // conversion from IEnumerable necessary to use indexing

    // this list will include all Colors including OS system colors
    colorList = Enum.GetValues(typeof(KnownColor))
       .Cast<knowncolor>()
       .ToList();

    // if you want only the Microsoft named colors, like 'AliceBlue
    // and not the colors defined by the OS theme, like 'ActiveBorder
    // use this to build the list
    //colorList = Enum.GetValues(typeof(KnownColor))
        //.Cast<KnownColor>()
        //.Where(clr => ! (Color.FromKnownColor(clr).IsSystemColor))
        //.ToList();

    rand = new Random(DateTime.Now.Ticks.GetHashCode());

    maxColorIndex = colorList.Count();

    for (int i = 0; i < 10; i++)
    {
        KnownColor randColor = getRandomColor();
        Console.WriteLine(randColor);
    }
}
 
Share this answer
 
v3
Comments
CPallini 6-Oct-14 15:58pm    
Dont' know why someone downvoted your solution, it looks a nice piece of code. Have my 5.
BillWoodruff 7-Oct-14 5:24am    
Thank you !
Thomas Daniels 7-Oct-14 11:49am    
Good answer, +5!
As a color has RGB data and all values (red, green and blue) are integers from 0 to 255 (0 and 255 included), you can use the Random class to generate three integers between 0 and 255.
C#
Random rand = new Random();
int max = byte.MaxValue + 1; // 256
int r = rand.Next(max);
int g = rand.Next(max);
int b = rand.Next(max);
Color c = Color.FromArgb(r, g, b);

rand.Next(max); returns an integer from 0 to 255, but we pass max (= 256) as argument because the argument of rand.Next is the exclusive upper bound, so if we use 256 here, it will include 255, but not 256.

More information about Random.Next: http://msdn.microsoft.com/en-us/library/System.Random.Next.aspx[^]
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 6-Oct-14 13:37pm    
Using any immediate constants like 256 is unacceptable. It's always better to introduce explicit constant (if not member, possibly read-only, or a variable).

In this case, replace "255" with "byte.MaxValue + 1".

Therefore, I up-voted it with my 4. :-)

—SA
Thomas Daniels 6-Oct-14 13:40pm    
Thanks for your comment! I edited my answer.
CPallini 6-Oct-14 13:48pm    
Why an immediate constant is an abomination?
Sergey Alexandrovich Kryukov 6-Oct-14 14:40pm    
I though it should be apparent for you. What if you need to change it? What, changing it in 3 or more places?
And the change is quite possible in this case. One may want to limit the range of the colors, the code can be required to adopt 16-bit colors, and so on...
—SA
CPallini 6-Oct-14 15:31pm    
Yes, it is indeed. It was just a silly question.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 6-Oct-14 13:40pm    
"Random color" should not be understood as "random colors taken from some set", such as named colors.
This advice would be good it was only a complement to the code generated random color values, as Solution 2 suggests.
—SA
BillWoodruff 6-Oct-14 13:58pm    
In this case the OP specifically wants Colors taken from the set of Colors in System.Drawing.Color :)
Sergey Alexandrovich Kryukov 6-Oct-14 14:43pm    
No. Maybe you misread this type. This is a set of colors, all 256x256x256x256 (ARGB). Don't mix it up with the types like System.Drawing.Colors, System.Drawing.System.Colors each representing subset of the color values represented by System.Drawing.Color. See the difference? :-)
—SA
BillWoodruff 6-Oct-14 14:52pm    
You're absolutely right, Sergey, the OP's use of "Color" (singular) does not justify my assumption that meant only the Known Color Enumeration contents ! Good catch.
Sergey Alexandrovich Kryukov 6-Oct-14 15:05pm    
:-)
A simple way for obtaining an opaque color
C#
Random rand = new Random();
int r = rand.Next(256);
int g = rand.Next(256);
int b = rand.Next(256);
Color col = Color.fromArgb(r,g,b);
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 6-Oct-14 14:47pm    
Same comment as my comment to Solution 2.
Some two members voted 2, probably because your solution repeats already available solution. But I know that you would not copy someone else's solution on purpose; most likely, it was a coincidence, and the post overlapped in time; so I voted my 4.
—SA
CPallini 6-Oct-14 15:32pm    
:-) I just copy myself. Thank you.
There's this, but it could use some work.

C#
public static class RandomColor
{
    private static readonly System.Random r ;
    private static readonly System.Reflection.PropertyInfo[] a ;

    static RandomColor
    (
    )
    {
        r = new System.Random() ;

        a = typeof(System.Drawing.Color).GetProperties ( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static ) ;

        return ;
    }

    public static System.Drawing.Color
    Next
    (
    )
    {
        return ( (System.Drawing.Color) a [ r.Next ( a.Length ) ].GetValue ( null , null ) ) ;
    }
}
 
Share this answer
 
The idea is to pass random values to the Color object itself. The following is the documentation for the Random class.

http://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx[^]

You can create your own random numbers, and then pass them as values of Red, Green and Blue in the Color object.

Since we're going to work between 0 - 255, so you will use this property on the Random object, Next(int, int).

C#
// create new instance
Random rand = new Random();
// would return between 0 - 255
int randomNumber = rand.Next(0, 255);


Now, you can get these values in three different variables. Then pass them as values to the Color object. Like this

C#
// include namespaces
using System;
using System.Drawing;

// create new instance
Color color = new Color();
// set the values of RED, GREEN and BLUE
color.R = randRed;
color.G = randGreen;
color.B = randBlue;

// use the color here in the code
// as a Color object of System.Drawing namespace.
 
Share this answer
 
Comments
Cesar Bretana Gonzalez 6-Oct-14 16:03pm    
Well, thanks to everyone to your help, all of you really help me people, thanks again...
the best and effiënt way of doing this is:

C#
Random rng = new Random();

Color.FromArgb(rng.next(-16777216, 0);


this will return a random color with 255 as the alpha value;
 
Share this answer
 
v2
Comments
Richard MacCutchan 24-Jan-18 5:07am    
More than THREE years too late. Please don't resurrect old answers; especially those that already have solutions.
Jan_Tamis 2-Mar-18 5:13am    
Well i find the awnser to ineffiënt so i thought i'll post a better solution.
Richard MacCutchan 2-Mar-18 5:52am    
Your answer is not better, in fact it is quite a bad suggestion.
Jan_Tamis 11-Mar-18 8:45am    
Can you then tell me why it is not a better awnser?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900