Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android/Java: Convert any string to color (hex)

Tags:

java

android

Is there any way to generate a color from any String in Java / Android like an Encrypt / Hash function?

Example: The String "Home" generates a color like "#FF1234".
The String "Sky" generates a color like "#00CC33" ...

Without randomize. So, the system will always calculate the same colors for that strings

Thanks

EDIT: The Strings are freely defined by the user

like image 265
Daniel Avatar asked Jun 08 '12 17:06

Daniel


2 Answers

the String.hashCode() will return an int value, so then it's just a matter of turning that into into a hex value.

String s = "Home";
String color = String.format("#%X", s.hashCode());
like image 117
stuckless Avatar answered Oct 14 '22 11:10

stuckless


With consistent opacity:

String opacity = "#99"; //opacity between 00-ff
String hexColor = String.format(
        opacity + "%06X", (0xFFFFFF & anyString.hashCode()));

Or using the new material design android Palette:
https://gist.github.com/odedhb/79d9ea471c10c040245e

like image 5
Oded Breiner Avatar answered Oct 14 '22 11:10

Oded Breiner