简体   繁体   中英

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

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

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());

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

Try looking here for how to create a message digest of your string.

http://www.mkyong.com/java/java-sha-hashing-example/

After you have created a message digest, use how many every of the bytes generated to create your color value. You could use least significant, most significant, anywhere in the middle.

I am guessing you are not trying to change the resource file.

Depends on how you want to do it to be honest. THere are millions of ways to accomplish it

For me, I would take the Ascii value of each character, add them all up, then convert it to hex. With that Said, to cover the case of too many characters, would mod it to the max size of a hex string. IE. FFFFFF so that way it wraps around and starts over.

//pseudocode
counter = 0;
foreach(char in string){
    counter+=(int)char;

}
counter = convertToHex(counter)%0xffffff;
string x = "#"+counter.toString();

AFter that i would store it into a string

string x = "#"+hexVal.toString();

them you could do with it what you wanted.

You can try something like:

String s = "Home";
byte[] b = s.getBytes("US-ASCII");
StringBuffer hexString = new StringBuffer();
for (int i=0;i<b.length;i++) {
    hexString.append(Integer.toHexString(0xFF & b[i]));
    }
String finalHex = "#" + hexString.substring(0,6);
System.out.println(finalHex);

Generates a hex : #486f6d

Similarly generate hex for all the String s you want and keep adding them up to a HashMap as a key-value pair.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM