Unique Persistent Colour Generation From StringsPosted on:
Ever wanted to assign a certain post, node or object a unique, persistent colour, based on the name? Well here’s how!
I recently wrote a post on how to generate unique colours, but this was for lists, and worked on a number. This post is different - it works with determining a colour based on a string. Once again, we’re using the HSL colour system - we have a set saturation and lightness, but change the hue based on some factor.
It’s a simple trick we’ll be using for this. Given a string, such as a name of an object, we’ll hash it, then use that number mod 360 to determine the hue. You can use any hash function you want, but you might need to tweak it to work with your inputs.
Originally I implemented Java’s .hashCode() String method, but found it did not lend itself to making good colours. You can see an example here:
And then for the rest of the code:
This just creates a bunch of strings, hashes them and generates some coloured boxes. Here is the result:
However, I didn’t find this made good enough colours - notice how the colours for “A” “B” and “C” are practically identical. Instead, I wrote a simple hash that simply added the char code of the character, but squared. This meant that each character produced a vastly different colour to the last.
As you can see, this produces much better results:
Why not play around and see what you can produce? If you have any similar insights or stories, put them in the comments!
Also, check out generating unique colours from a count!