Click here to Skip to main content
15,896,912 members
Articles / Programming Languages / C#
Tip/Trick

Random Color Generator

Rate me:
Please Sign up or sign in to vote.
4.67/5 (15 votes)
15 Sep 2011CPOL3 min read 86K   15  
This is an old version of the currently published tip/trick.


Introduction


I wanted to create a random color generator.

The initial application was a plot color attribution for a graphic control.


I wanted to be able to put some weight to some color to ensure to stay away from them (like the background color). I haven’t found anything that does that. I decided to code it myself.


The Solution


I started from the excellent code found here on code project from  Guillaume Leparmentier: http://www.codeproject.com/KB/recipes/colorspace1.aspx?msg=4018256#xx4018256xx

In fact, it was so good that I kept 99.9% of it and mainly just added 2 others classes (plus a Form to test).


I only added/modify:



  • I changed Color class used from WinForm (System.Drawing) to WPF (System.Windows.Media)
  • I added Distance calculation in CIELab.cs
  • I added a helper function GetColorDistanceCIELab in ColorSpaceHelper class
  • I added ColorGenerator, ColorRatio class and FormTestColorGenerator.

The class is based on random color generation with auto adjustable distance tolerance. High distance tolerance at start but decrease while adding new colors.

The code references Framework.Net 4.0 (and WPF) and the project is VS2010.


References



Usage


The main usage is defined in the header comments of ColorGenerator class

Comments copy:


C++
// Main usage:
    ColorGenerator colorGenerator = new ColorGenerator();
    
    // Faster, little bit more color with less distance 
    colorGenerator.Speed = 50; 
    
    // My background, 4 to stay far away 
    colorGenerator.UsedColors.Add(new ColorGenerator.ColorRatio(System.Windows.Media.Colors.Black, 4)); 
    // No White
    colorGenerator.UsedColors.Add(new ColorGenerator.ColorRatio(System.Windows.Media.Colors.White, 1.2)); 
    
    // Grid Color
    colorGenerator.UsedColors.Add(new ColorGenerator.ColorRatio(System.Windows.Media.Colors.LightGray, 1)); 
    System.Windows.Media.Color c = colorGenerator.GetNextColor();

Conclusion


Hope it helps some

License

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


Written By
Software Developer IREQ - Hydro-Quebec
Canada Canada
Hi,

I'm a french Canadian software developer.
Work at Hydro-Quebec / IREQ.
Live in Sainte-Julie, Quebec, Canada (South shore of Montreal)

WebPage: http://www.ericouellet.com
GMail: ericouellet2

Salut!

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.